Powershell - Script weirdness

So I have the code below, generated a couple years back with help from the EE community.  However it's acting weird.. I'm trying to convert this into an EXE for distribution to the rest of the IT department.  If I run the code from within the ISE it performs exactly as it should... completing 100% successfully.
However if I run the converted (ps2exe.ps1) executable it completes successfully but never populates a few specific attributes: streetaddress, city, zip and scriptpath.  Also if I call the new_user.ps1 from a Powershell window (opened as admin) it does the exact same thing.  Performs all functions except the streetaddress, city, zip and scriptpath.


#Create-NewADUserO365.ps1
#3/3/15 Benjamin Hart, Unified Brands, Inc
#Created with Powershell ISE
#This powershell script will create a domain user object using a format of lastname, firstname, a SAM of first initial + last name
#It will also populate displayname, a default password, office and both proxyaddresses, the primary as used in your org and the 
#Dover required O365 one.  It will also verify the primary proxy address is not already used.
#With set-aduser you can alter almost any attribute of the user.

$theOU = read-host "Enter the OU name"
$Surname = read-Host "Enter the surname"
$GivenName = read-host "Enter first name"
$DisplayName = "$Surname, $GivenName"
$Password = "December1"
$name = $GivenName.substring(0,1)+$Surname
$proxyaddress = read-host "Enter the proxy address in full"


Import-Module activedirectory
import-module servermanager



	#Edit the SearchBase to match your organization
	$myOU = Get-AdOrganizationalUnit -Filter "Name -eq '$theOU'" -Searchbase 'OU=People,DC=Domain,DC=Root01,DC=org'
	
#Below verifies the Proxyaddress is not already present	
Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress}
	$found=Get-ADuser  -filter * -Properties ProxyAddresses|
     Where-Object{
        $_.proxyaddresses | 
             Where-Object{ $_ -eq $ProxyAddress }}

while (Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress})
{
  $proxyaddress = read-host "$proxyaddress is already in use, please try another one"
}
Write-Host "$proxyaddress is not used yet."

#Edit your locations if you choose to use this part
Switch ($Office)  {
    "Michigan" {
        $Street = "123 Main st"
        $City = "Weidman"
        $State = "Michigan"
        $Zip = "48898"
        $scriptpath = "\\difc\netlogon\milogin1.bat"
}
    "Mississippi"  {
        $Street = "123 Main st"
        $City = "Jackson"
        $State = "Mississippi"
        $Zip = "39272"
        $scriptpath = "\\difc\netlogon\adlogin.bat"
        }
    "Oklahoma"  {
        $Street = "123 Main st"
        $City = "Pryor"
        $State = "Oklahoma"
        $Zip = "74361"
        $scriptpath = "\\difc\netlogon\oklogin.bat"
        }
    "Georgia"  {
        $Street = "123 Main st"
        $City = "Conyers"
        $State = "Georgia"
        $Zip = "30013"
}
}
#Edit the below to match your domain(s)
$DoverProxyAddress = "$($givenname.substring(0,1))$surname-$("unifiedbrands")-$("net")@company.mail.onmicrosoft.com"
$Description = read-host "Enter persons description"
$jobtitle = read-host "Enter the Job Title"
#Edit the below to match your locations
$office = read-host "Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote"
$department = read-host "Enter the users Department"

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -force) -enabled:$false
set-aduser $name -emailaddress $proxyaddress -Description $Description -Title $jobtitle -Office $office -UserPrincipalName $proxyaddress -Department $department -Company "Company, Inc"
set-aduser $name -StreetAddress $Street -city $city -state $state -PostalCode $zip
set-aduser $name -ScriptPath $scriptpath 
Set-ADUser $name -Replace @{employeeType="EMPLOYEE"}
set-aduser $name -add @{proxyaddresses = ("SMTP:")+"$proxyaddress"}
set-aduser $name -add @{ProxyAddresses = ("smtp:")+"$doverproxyaddress"}

 	
get-aduser $name 

Open in new window

LVL 14
Ben HartAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ben HartAuthor Commented:
Oh to help clarify too, I've used the same domain account running the script in both formats. The account used has domain admin rights.
FOXActive Directory/Exchange EngineerCommented:
For lines 79 and 80 you want the command to run against the samaccountname .  You have the command running against your $name variable which consists of your first name and last name.  If you run the command in powershell by itself inputting a first and last name it will not work.  If you run the command in powershell using the username or samaccountname it will edit the properties of the city, street, and postalcode.
Maybe in line 16 you want to add  $samaccountname = read-host "Enter the username"
Then in lines 79 and 80 you put set-aduser $samaccountname

Try that
FOXActive Directory/Exchange EngineerCommented:
Disregard.  I just realized your $name variable is the samaccountname
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Ben HartAuthor Commented:
Heh I was just about to comment lol.  Yeah I am specifying our Samaccountname in the New-Aduser line (77).
footechCommented:
I believe I've seen some issues when modifying attributes right after the account is created (though it might have been creating a mailbox).  Put a Start-Sleep for a few seconds right after line 77 and see if it fixes it.  If so you can play with the time to see what the minimum is.
Ben HartAuthor Commented:
I added 15 and 30 second sleep-times.  The info still didn't appear.  But since you mentioned that Foo, it happens when I run the code within ISE.. I have to give ADUC about 30-45 seconds before everything populates. This exe business though.. I need to get this ps1 into a more usable format by helpdesk level folks, besides that I don't want them having the source.
FOXActive Directory/Exchange EngineerCommented:
Ben, are these Office 365 users?
Ben HartAuthor Commented:
Sort of.. it's Exchange Online DirSYnc'ing from on-premise AD. We do not create users in 365.
FOXActive Directory/Exchange EngineerCommented:
The command may be different then.  For lines 79 and 80, try set-user $username

ref link:
https://community.office365.com/en-us/f/613/t/200717
footechCommented:
I've never seen a difference in behavior using ISE or the console with those commands (and just did a test).
One thing I'd like to make sure of is that this isn't just a display issue, like when ADUC hasn't refreshed its data.

Also, why all the separate Set-ADUser calls (not sure if it's a factor or not)?  It'd be more efficient to combine it all into one.  Try putting as much as you can in the New-ADUser command and see if it works.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
footechCommented:
@Foxluv - With DirSynced users, just about everything is done on the on-premise AD.  You won't use Exchange cmdlets here.
Ben HartAuthor Commented:
Thanks guys, Foo I separated out all the set-aduser cmdlets to help in troubleshooting. What grinds me gears in this scenario is that subsequent changes are applied, like setting the employeetype and the proxyaddresses work.. but street/city/zip which is BEFORE the employeetype is not set.  This is bugging me to no end.
Ben HartAuthor Commented:
OK I fixed it.. no clue how really but it works after a little code cleanup.  Here's the new script.

#Create-NewADUserO365.ps1 version 2
#3/3/15 Benjamin Hart, Unified Brands, Inc
#Created with Powershell ISE
#This powershell script will create a domain user object using a format of lastname, firstname, a SAM of first initial + last name
#It will also populate displayname, a default password, office and both proxyaddresses, the primary as used in your org and the 
#Parent Company required O365 one.  It will also verify the primary proxy address is not already used.
#With set-aduser you can alter almost any attribute of the user.


Import-Module activedirectory
import-module servermanager 

$theOU = read-host "Enter the OU name"
$Surname = read-Host "Enter the surname"
$GivenName = read-host "Enter first name"
$DisplayName = "$Surname, $GivenName"
$Password = "December1"
$name = $GivenName.substring(0,1)+$Surname
$company = "Company"
$proxyaddress = read-host "Enter the proxy address in full"

	#Edit the SearchBase to match your organization
	$myOU = Get-AdOrganizationalUnit -Filter "Name -eq '$theOU'" -Searchbase 'OU=People,DC=DIFC,DC=Root01,DC=org'
	
#Below verifies the Proxyaddress is not already present	
Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress}
	$found=Get-ADuser  -filter * -Properties ProxyAddresses|
     Where-Object{
        $_.proxyaddresses | 
             Where-Object{ $_ -eq $ProxyAddress }}

while (Get-ADuser  -filter * -Properties ProxyAddresses|?{$_.proxyaddresses -contains $proxyaddress})
{
  $proxyaddress = read-host "$proxyaddress is already in use, please try another one"
}
Write-Host "$proxyaddress is not used yet."


#Edit your locations if you choose to use this part
#Edit the below to match your domain(s)

$DoverProxyAddress = "$($givenname.substring(0,1))$surname-$("company")-$("net")@parentcompany.mail.onmicrosoft.com"
$Description = read-host "Enter persons description"
$jobtitle = read-host "Enter the Job Title"
#Edit the below to match your locations
$office = read-host "Enter the user's location, Michigan, Mississippi, Georgia, Oklahoma or Remote"
Switch ($Office)  {
    "Michigan" {
        $Street = "123 main st."
        $City = "Weidman"
        $State = "Michigan"
        $Zip = "48898"
        $scriptpath = "\\difc\netlogon\milogin1.bat"
}
    "Mississippi"  {
        $Street = "123 main st"
        $City = "Jackson"
        $State = "Mississippi"
        $Zip = "39272"
        $scriptpath = "\\difc\netlogon\adlogin.bat"
        }
    "Oklahoma"  {
        $Street = "123 main st"
        $City = "Pryor"
        $State = "Oklahoma"
        $Zip = "74361"
        $scriptpath = "\\difc\netlogon\oklogin.bat"
        }
    "Georgia"  {
        $Street = "123 main st"
        $City = "Conyers"
        $State = "Georgia"
        $Zip = "30013"
}
}

$department = read-host "Enter the users Department"

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname `
 -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -force) -enabled:$false -emailaddress $proxyaddress `
 -Description $Description -Title $jobtitle -Office $office -UserPrincipalName $proxyaddress -Department $department `
 -Company $company -StreetAddress $Street -city $city -state $state -PostalCode $zip -ScriptPath $scriptpath

 
set-aduser $name -Replace @{employeeType="EMPLOYEE"}

start-sleep -seconds 5

Set-ADUser $name 
set-aduser $name -add @{proxyaddresses = ("SMTP:")+"$proxyaddress"}
set-aduser $name -add @{ProxyAddresses = ("smtp:")+"$doverproxyaddress"}

 	
get-aduser $name

Open in new window

footechCommented:
It appears that putting it all into the New-ADUser command worked.  I don't really have an explanation for the issue, but I would suspect it's something to do with timing.
Ben HartAuthor Commented:
Bad thing is.. it WAS working prior to me trying to create an EXE then I discovered the fault.
Ben HartAuthor Commented:
Footech provided the help pointing to combining all the set-aduser cmdlets into the new-aduser but I also re-org'd the array which helped it run w/o error after converting to EXE.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.