Link to home
Start Free TrialLog in
Avatar of Hans de Jongh
Hans de JonghFlag for Netherlands

asked on

Powershell variable to file for use in other scripts

Hello,

I have a number of script which all use the same variables:

#Enter Companyname
$Companyname = Read-Host "Enter the companyname this will be used for the ou creation: ouCompanyname"

Now i want to be able to give this variable one time and then use it in the series of scripts which the user has to execute.
The problem is that the computer needs to be rebooted after a script..

So what is the best approach for this?

Regards

Hans
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image


You'd have to store it in either a configuration file or the registry. Basically something persistent.

Chris
Avatar of Hans de Jongh

ASKER

hee genius:)

thanks, so something with out-file or better use a csv file?

It depends on complexity. If you have a large number of variables, Export-Csv. Imagine you had something like this:

[code]
$Settings = New-Object PsObject -Property @{
  Path = "C:\Scripts\";
  Status = "Executing Script 1";
  StepNumber = 1
}

$Settings | Export-Csv "settings.csv"
[/code]

Then the next script can pick that up and carry on:

[code]
$Settings = Import-Csv "settings.csv"
$Settings.StepNumber++
$Settings.Status = "Executing Script 2"
# Update the settings file
$Settings | Export-Csv "settings.csv"
[/code]

I bet the code tags don't work...

Chris
well that`s my dream script but as i`m still a scripting n00b i dont think i`ll manage.

i`m making a series of scripts (like 10) that after the install of windows 2008 R2 do everything:
installing/configuring AD/Exchange/Shares/GPO`s

the number of variables that need to be stored is below 10...

My dreamscript would be that you start up the script and then after reboot would continue untill it has done everything, but for now it is running 10 seperate scripts.

But if i could use the same variables each time that would be alot easier already!

No reason you can't do that. Lets see, steps might go like this:

1. Reads / requests configuration variables (I'd have script parameters, but that's just me)


[CmdLetBinding()]
Param(
  [Parameter(Mandatory = $True)]
  [String]$RequiredParameter1,
  [String]$OptionalParameter1,
  [Int32]$ScriptStep = 1
)


2. Store parameters in a PsObject and drop them to a file for the next run:


$Settings = New-Object PsObject @{
  RequiredParameter1 = $RequiredParameter1,
  OptionalParameter1 = $OptionalParameter1
}
$Settings | Export-Csv "settings.csv"


3. Do stuff for this stage


Function Do-StuffFor1 {
  Write-Host "Making stage 1 changes"
  # Insert content of first script
}

Function Do-StuffFor2 {
  Write-Host "Making stage 2 changes"
  # Insert content of second script
}

Switch ($ScriptStep) {
  1 { Do-StuffFor1 }
  2 { Do-StuffFor2 }
}


4. Make the script start next boot:


New-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript" -Value "PowerShell.exe -Command { C:\Scripts\setup.ps1 -ScriptStep 2 }"


The last script step would wipe out the Run value and perform any other cleanup it needed.

Chris
thanks chris, i`ll look into it! to behonest i have no programming skills or experience what so ever. But i already have come this far, cause all the 10 scripts work:)

but if i assume correctly:

$RequiredParameter1 this would contain for example the value company name
$OptionalParameter1 this would contain for example the user password?

so i  would put in $requiredparameter1 in function do-stufffor1 it would read it from the csv file?

Yep it could if you want. They're completely flexible, you can make them up :)

Exactly how they're used depends on what each script does. Can you give an example (cut-down / obscured)? Might be easier for you to apply my examples if you can see them in context :)

Chris
here, i still need to build in checks to see if everything went ok..

The script which i didnt copy are the on with no need for the variables...


Script 1

#This is the first script you can run after the creation of a new domaincontroller.
#First installation of some features
import-module servermanager
add-windowsfeature telnet-client,Backup-features

#Now lets format some drives which weren't in the setup.
Write-host "WARNING DRIVES D:/E:/F: will be formated"
write-host "Formating D: drive starts now."
Start-Sleep -s 1
format d: /fs:NTFS /v:Data /Q
write-host "Formating E: drive starts now."
Start-Sleep -s 1
format e: /fs:NTFS /v:MDB /Q
write-host "Formating F: drive starts now."
Start-Sleep -s 1
format f: /fs:NTFS /v:LOG /Q

#Now lets change the computername.
$Companyname = Read-Host "Enter the companyname this will be used for the servername"
$servername = $companyname + "DC01"

write-host "this servername will be used: $servername"
Start-Sleep -s 1

$oComputerSystem = Get-WmiObject win32_computersystem
$oComputerSystem.Rename( "$servername" )

write-host "I`m done, let me reboot the server for you."
Start-Sleep -s 1
write-host "Rebooting"
start-sleep -s 1
shutdown /r /t 0

Script 2
# This script installs and configures a new AD on this server. It assumes that this is a complete new forest.
# First we install the necessary roles.

Write-Host "Installing the necessary roles"
import-module servermanager
add-windowsfeature ad-domain-services

Write-Host "ok everything went well!, now I need to know somethings!"
Start-Sleep 2
$Companyname = Read-Host "Enter the companyname this will be used for AD name"
Start-Sleep 2
$domaindnsname = $companyname + ".local"
Write-Host "thanks, so the domainname will be $domaindnsname is that correct?"
Write-Host "Press any key to continue ..."
$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

$safemodeadminpassword = Read-Host "Thanks now provide a Domain restore password (PUT IT IN SHAREPOINT)"
Start-Sleep 2
Write-Host "this is the password you gave me! $safemodeadminpassword , if correct please press any key"
$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Write-Host "Thanks now i have everything i need, dont worry i`ll install a dns server for you!"

dcpromo /unattend /installdns=yes /newdomain=forest /newdomaindnsname=$domaindnsname /domainnetbiosname=$companyname /ReplicaOrNewDomain=domain /forestlevel=4 /domainlevel=4 /rebootoncompletion=yes /safemodeadminpassword=$safemodeadminpassword

Script 3

#This script installs features, sets windows update, creates the standard OU structure, creates the admin accounts, data folders, shares and the correct ACL`s
#This script should also test to see if active directory snap-in is loaded, but currently i dont know how to do that!
#Importing activedirectory module!

Import-Module ActiveDirectory
#Enter Companyname
$Companyname = Read-Host "Enter the companyname this will be used for the ou creation: ouCompanyname"

#Enter the default password for the admin users
$adminpassword = Read-Host "Enter password for the Admin users" -AsSecureString

#change windows update settings
cscript.exe c:\scripts\windowsupdate.vbs

#Create new Organizational units.

New-ADOrganizationalUnit -Name ou$Companyname -Path "DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouComputers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouGroups -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouUsers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouLaptops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouDesktops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouRDServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouDomainControllers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouAppServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouDistribution -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouSecurity -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name Apps -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name Shares -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name Mailbox -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name "Start Menu" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouInternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouExternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouMailOnlyUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouContacts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouSaAccounts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
New-ADOrganizationalUnit -Name ouAdministrators -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false

#Create new Security Groups
New-ADGroup -Name "grRDUsers" -SamAccountName grRDUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers"
New-ADGroup -Name "grRDHomeUsers" -SamAccountName grRDHomeUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop Home users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers from external locations"
New-ADGroup -Name "grSharedData" -SamAccountName grSharedData -GroupCategory Security -GroupScope Global -DisplayName "Shared Data users " -Path "ou=Shares,ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group have access to the Company`s Shared data"

#Create admin user accounts
New-ADUser -Name "admxxx" -samaccountname xxxx -givenname "xxxx" -surname "xxxxx" -displayname "Adm xxxx" -path "ou=ouAdministrators,ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -Enabled $true -AccountPassword $adminpassword -ChangePasswordAtLogon $true

#Add admin accounts to the administrators group
add-adgroupmember Administrators xxx

#Now we are going to create the data, profile and user home directies.
new-item d:\"$companyname Data" -type directory
new-item d:\"$companyname Data"\"Shared_Data" -type directory
new-item d:\"$companyname Data"\"RDProfiles" -type directory
new-item d:\"$companyname Data"\"Profiles" -type directory
new-item d:\"$companyname Data"\"Home" -type directory

net share "Shared_Data$=d:\$companyname Data\Shared_Data" "/grant:everyone,full"
net share "RDProfiles$=d:\$companyname Data\RDProfiles" "/grant:everyone,full"
net share "Profiles$=d:\$companyname Data\Profiles" "/grant:everyone,full"
net share "Home$=d:\$companyname Data\Home" "/grant:everyone,full"

icacls "d:\$companyname data" /inheritance:d
icacls "d:\$companyname data" /remove:g users
icacls "d:\$companyname Data\Shared_Data" /grant:r grSharedData:"(OI)(CI)M"
icacls "d:\$companyname Data\RDProfiles" /grant:r users:rd
icacls "d:\$companyname Data\Profiles" /grant:r users:rd
icacls "d:\$companyname Data\Home" /grant:r users:rd

script 5

Write-host "this script installs exchange"
Write-host "with the following roles: CAS/HUB/Mailbox"
write-host "This script assumes that you have got 4 drives:"
write-host " c: (system) d:(Data) e:(MDB) f:(log)"
write-host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

write-host "thank you, now lets set some variables"
write-host "Use the same companyname as you did for the newADEnviroment"
$Companyname = Read-Host "Enter the companyname: ouCompanyname"

new-item E:\"$companyname Exchange MDBs" -type directory
new-item F:\"$companyname Exchange Logs" -type directory
new-item E:\"$companyname Exchange MDBs"\"Mailbox" -type directory
new-item E:\"$companyname Exchange MDBs"\"PublicFolder" -type directory
new-item F:\"$companyname Exchange Logs"\"Mailbox" -type directory
new-item F:\"$companyname Exchange Logs"\"PublicFolder" -type directory
new-item F:\"$companyname ExchangeSystem Logs" -type directory

$mdbpath = "E:\$companyname Exchange MDBs\Mailbox\$companyname.edb"
$logpath = "E:\$companyname Exchange Logs\Mailbox"
$mdbname = "$Companyname MailboxDB"

Set-Service NetTcpPortSharing -StartupType Automatic

G:\setup.com /mode:install /roles:"mb,ht,ca" /mdbname:$mdbname /dbfilepath:$mdbpath /logfolderpath:$logpath /organizationname:$Companyname

script 7

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
#Lets get some variables

$externalurl = Read-Host "please tell me the a-record which the customer uses for webmail"
$Companyname = Read-Host "Enter the companyname"
$domainname = Read-Host "Enter the maildomain name something like company.com"
$sendconnectorname = $Companyname + " Sendconnector"

#remove the limitations for messages and mailbox size on the mailbox store.
Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendReceiveQuota unlimited
Get-MailboxDatabase | set-mailboxdatabase -IssueWarningQuota unlimited
Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendQuota unlimited

#set the deleteditemretention to 30 days.
Get-MailboxDatabase | set-mailboxdatabase -DeletedItemRetention 30

#enabling circularlogging
Get-MailboxDatabase | set-mailboxdatabase -CircularLoggingEnabled 1

#lets make a sendconnector
new-sendconnector -name $sendconnectorname -addressspace * -fqdn $externalurl -smarthosts mx1.blaaat.com -maxmessagesize 20480

#next we make a new accepteddomain

new-accepteddomain $companyname -domaintype authoritative -domainname $domainname
set-accepteddomain $companyname -makedefault $true

#ok time to set the right emailaddresspolicy
get-emailaddresspolicy | set-emailaddresspolicy -enabledprimarysmtpaddresstemplate "smtp:%m@$domainname"

#now we want to recieve mail from the outside so we need to add anonymoususers to the right recieveconnector
Get-ReceiveConnector | where {$_.identity -like "*Default*"} | Set-ReceiveConnector -PermissionGroups anonymoususers,exchangeusers,exchangeservers,exchangelegacyservers -MaxMessageSize 20mb

#owa rules so no need to wait any longer to enable it!
Enable-OutlookAnywhere -ExternalHostname $externalurl -SSLOffloading $false -DefaultAuthenticationMethod 'Basic'

#now lets put in the right exchange certificate
Write-Host "Please make sure that in the folder c:\scripts\ the certificate is present"
$certificatename = $externalurl + ".pfx"
Write-Host "the filename should be in the following format $certificatename"
Write-Host "Press any key to continue (if you are sure the right file is in the right location..."
$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Start-Sleep 2
$certpass = Read-Host "please provide the password for the pfx file" -AsSecureString
Import-ExchangeCertificate -FileData ([Byte[]]$(Get-Content -Path "c:\scripts\$certificatename" -Encoding byte -ReadCount 0)) -Password:$certpass
get-exchangecertificate | where {$_.subject -like "*$externalurl*"} | enable-exchangecertificate -service imap,pop,smtp,iis -force

#OK!!! allmost there, lets make sure those spammers dont get trought"

& 'C:\Program Files\Microsoft\Exchange Server\V14\Scripts\install-AntispamAgents.ps1'
Write-Host "Watch out!! I`m going to restart the transportservice, are ok with that???"
Write-Host "just smash the keyboard if you are!!!!"
$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Restart-Service msexchangetransport

#m$ always likes to give you toooooo much, so i need to disable some things.."
Set-ContentFilterConfig -Enabled $false
Set-IPAllowListConfig -enabled $false
Set-IPblockListConfig -enabled $false
Set-IPBlockListProvidersConfig -enabled $false
Set-IPAllowListProvidersConfig -enabled $false
Set-SenderFilterConfig -enabled $false
Set-SenderIdConfig -enabled $false
Set-SenderReputationConfig -enabled $false
Set-RecipientFilterConfig -RecipientValidationEnabled $true

# finalizing! lets get those systemlogs in the right place!
Get-MailboxServer | Set-MailboxServer -MessageTrackingLogPath "f:\$companyname ExchangeSystem Logs\messagetrackinglog"
Get-TransportServer | Set-TransportServer -ConnectivityLogPath "f:\$companyname ExchangeSystem Logs\connectivitylog"
Get-TransportServer | Set-TransportServer -SendProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpSend"
Get-TransportServer | Set-TransportServer -ReceiveProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpRecieve"

script 8

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
$defaultpass = Read-Host "Please provide the firsttime password" -AsSecureString
$companyname = Read-Host "Please provide companyname"

$userou = "$companyname" + ".local/ou" + $companyname + "/ouUsers/ouInternalUsers"
$csvfile = "c:\scripts\users.csv"

Import-CSV $CSVFile | ForEach-Object -Process {New-Mailbox -Name $_.Name -FirstName $_.FirstName -LastName $_.LastName -displayname $_.displayname -alias $_.alias  -UserPrincipalName $_.upn -organizationalunit "$userou" -Password $defaultpass | set-user -city $_.city -company $_.company -countryorregion $_.countryorregion -fax $_.fax -mobilephone $_.mobilephone -phone $_.phone -postalcode $_.postalcode -streetaddress $_.streetaddress -title $_.title}

Open in new window


This is the kind of thing I had in mind.

You'll probably find I've overlooked things here so it needs quite careful testing.

Chris
#Requires -version 2.0

<#
  .Synopsis
    This script performs initial setup of a domain controller
  .Description
    This script performs initial setup of a domain controller
  .Parameter CompanyName
    The company name
  .Parameter RestoreModePassword
    The password used when booting into Restore Mode
  .Parameter AdministratorPassword
    Set as the Active Directory Administrator password.
  .Parameter DefaultUserPassword
    The default password for user accounts created by this script.
  .Parameter MailDomain
    The e-mail domain name
  .Parameter WebmailFQDN
    Used in the URL to access web-mail and used to obtain the certificate
  .Parameter ConfigurationFile
    A CSV formatted file containing all required parameters.
  .Parameter ScriptStep
    Helps the script progress across reboot
#>

[CmdLetBinding()]
Param(
  # Company Name
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$CompanyName,

  # Restore Mode (Safe Mode) password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$RestoreModePassword,

  # Administrator password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$AdministratorPassword,

  # Default user passsword
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$DefaultUserPassword,

  # Mail Domain
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$MailDomain,

  # Webmail FQDN
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$WebmailFQDN,

  # Automatic configuration (from file)
  [Parameter(Mandatory = $True, ParameterSetName = "AutoConfig")]
  [ValidateScript( { Test-Path $_ } )]
  [String]$ConfigurationFile,

  # Script Step
  [Parameter(ParameterSetName = "")]
  [Int32]$ScriptStep = 1
)

#
# Functions
#

Function Start-Setup1 {

  #This is the first script you can run after the creation of a new domaincontroller.
  #First installation of some features
  Import-Module servermanager
  Add-WindowsFeature telnet-client, Backup-features

  #Now lets format some drives which weren't in the setup.
  Write-host "WARNING DRIVES D:/E:/F: will be formated"
  write-host "Formating D: drive starts now."
  Start-Sleep -s 1
  format d: /fs:NTFS /v:Data /Q
  write-host "Formating E: drive starts now."
  Start-Sleep -s 1
  format e: /fs:NTFS /v:MDB /Q
  write-host "Formating F: drive starts now."
  Start-Sleep -s 1
  format f: /fs:NTFS /v:LOG /Q

  #Now lets change the computername.
  $servername = "$($CompanyName)DC01"

  write-host "this servername will be used: $servername"
  Start-Sleep -s 1

  $oComputerSystem = Get-WmiObject win32_computersystem
  $oComputerSystem.Rename( "$servername" )

  write-host "I`m done, let me reboot the server for you."
  Start-Sleep -s 1
  write-host "Rebooting"
  start-sleep -s 1
  shutdown /r /t 0

}

Function Start-Setup2 {

  # This script installs and configures a new AD on this server. It assumes that this is a complete new forest.
  # First we install the necessary roles.

  Write-Host "Installing the necessary roles"
  import-module servermanager
  add-windowsfeature ad-domain-services

  Write-Host "ok everything went well!, now I need to know somethings!"
  Start-Sleep 2
  $domaindnsname = "$CompanyName.local"
  Write-Host "thanks, so the domainname will be $domaindnsname is that correct?"
  Write-Host "Press any key to continue ..."
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  Write-Host "Thanks now i have everything i need, dont worry i`ll install a dns server for you!"

  dcpromo /unattend /installdns=yes /newdomain=forest /newdomaindnsname=$domaindnsname /domainnetbiosname=$CompanyName /ReplicaOrNewDomain=domain /forestlevel=4 /domainlevel=4 /rebootoncompletion=yes /safemodeadminpassword=$RestorModePassword

}

Function Start-Setup3 {

  #This script installs features, sets windows update, creates the standard OU structure, creates the admin accounts, data folders, shares and the correct ACL`s
  #This script should also test to see if active directory snap-in is loaded, but currently i dont know how to do that!
  #Importing activedirectory module!

  Import-Module ActiveDirectory

  #change windows update settings
  cscript.exe c:\scripts\windowsupdate.vbs

  #Create new Organizational units.

  New-ADOrganizationalUnit -Name ou$Companyname -Path "DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouComputers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouGroups -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouUsers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouLaptops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDesktops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouRDServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDomainControllers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAppServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDistribution -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSecurity -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Apps -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Shares -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Mailbox -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name "Start Menu" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouInternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouExternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouMailOnlyUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouContacts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSaAccounts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAdministrators -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false

  #Create new Security Groups
  New-ADGroup -Name "grRDUsers" -SamAccountName grRDUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers"
  New-ADGroup -Name "grRDHomeUsers" -SamAccountName grRDHomeUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop Home users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers from external locations"
  New-ADGroup -Name "grSharedData" -SamAccountName grSharedData -GroupCategory Security -GroupScope Global -DisplayName "Shared Data users " -Path "ou=Shares,ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group have access to the Company`s Shared data"

  #Create admin user accounts
  New-ADUser -Name "admxxx" -samaccountname xxxx -givenname "xxxx" -surname "xxxxx" -displayname "Adm xxxx" -path "ou=ouAdministrators,ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -Enabled $true -AccountPassword $AdministratorPassword -ChangePasswordAtLogon $true

  #Add admin accounts to the administrators group
  add-adgroupmember Administrators xxx

  #Now we are going to create the data, profile and user home directies.
  new-item d:\"$companyname Data" -type directory
  new-item d:\"$companyname Data"\"Shared_Data" -type directory
  new-item d:\"$companyname Data"\"RDProfiles" -type directory
  new-item d:\"$companyname Data"\"Profiles" -type directory
  new-item d:\"$companyname Data"\"Home" -type directory

  net share "Shared_Data$=d:\$companyname Data\Shared_Data" "/grant:everyone,full"
  net share "RDProfiles$=d:\$companyname Data\RDProfiles" "/grant:everyone,full"
  net share "Profiles$=d:\$companyname Data\Profiles" "/grant:everyone,full"
  net share "Home$=d:\$companyname Data\Home" "/grant:everyone,full"

  icacls "d:\$companyname data" /inheritance:d
  icacls "d:\$companyname data" /remove:g users
  icacls "d:\$companyname Data\Shared_Data" /grant:r grSharedData:"(OI)(CI)M"
  icacls "d:\$companyname Data\RDProfiles" /grant:r users:rd
  icacls "d:\$companyname Data\Profiles" /grant:r users:rd
  icacls "d:\$companyname Data\Home" /grant:r users:rd

}

Function Start-Setup5 {

  Write-host "this script installs exchange"
  Write-host "with the following roles: CAS/HUB/Mailbox"
  write-host "This script assumes that you have got 4 drives:"
  write-host " c: (system) d:(Data) e:(MDB) f:(log)"
  write-host "Press any key to continue ..."
  $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  new-item E:\"$companyname Exchange MDBs" -type directory
  new-item F:\"$companyname Exchange Logs" -type directory
  new-item E:\"$companyname Exchange MDBs"\"Mailbox" -type directory
  new-item E:\"$companyname Exchange MDBs"\"PublicFolder" -type directory
  new-item F:\"$companyname Exchange Logs"\"Mailbox" -type directory
  new-item F:\"$companyname Exchange Logs"\"PublicFolder" -type directory
  new-item F:\"$companyname ExchangeSystem Logs" -type directory

  $mdbpath = "E:\$companyname Exchange MDBs\Mailbox\$companyname.edb"
  $logpath = "E:\$companyname Exchange Logs\Mailbox"
  $mdbname = "$Companyname MailboxDB"

  Set-Service NetTcpPortSharing -StartupType Automatic

  G:\setup.com /mode:install /roles:"mb,ht,ca" /mdbname:$mdbname /dbfilepath:$mdbpath /logfolderpath:$logpath /organizationname:$Companyname
}

Function Start-Setup7 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
  #Lets get some variables

  $sendconnectorname = "$Companyname Sendconnector"

  #remove the limitations for messages and mailbox size on the mailbox store.
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendReceiveQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -IssueWarningQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendQuota unlimited

  #set the deleteditemretention to 30 days.
  Get-MailboxDatabase | set-mailboxdatabase -DeletedItemRetention 30

  #enabling circularlogging
  Get-MailboxDatabase | set-mailboxdatabase -CircularLoggingEnabled 1

  #lets make a sendconnector
  new-sendconnector -name $sendconnectorname -addressspace * -fqdn $WebmailFQDN -smarthosts mx1.blaaat.com -maxmessagesize 20480

  #next we make a new accepteddomain
  
  new-accepteddomain $companyname -domaintype authoritative -domainname $MailDomain
  set-accepteddomain $companyname -makedefault $true

  #ok time to set the right emailaddresspolicy
  get-emailaddresspolicy | set-emailaddresspolicy -enabledprimarysmtpaddresstemplate "smtp:%m@$MailDomain"

  #now we want to recieve mail from the outside so we need to add anonymoususers to the right recieveconnector
  Get-ReceiveConnector | where {$_.identity -like "*Default*"} | Set-ReceiveConnector -PermissionGroups anonymoususers,exchangeusers,exchangeservers,exchangelegacyservers -MaxMessageSize 20mb

  #owa rules so no need to wait any longer to enable it!
  Enable-OutlookAnywhere -ExternalHostname $externalurl -SSLOffloading $false -DefaultAuthenticationMethod 'Basic'

  Import-ExchangeCertificate -FileData ([Byte[]]$(Get-Content -Path "c:\scripts\$WebmailFQDN.pfx" -Encoding byte -ReadCount 0)) -Password:$certpass
  get-exchangecertificate | where {$_.subject -like "*$WebmailFQDN*"} | enable-exchangecertificate -service imap,pop,smtp,iis -force

  #OK!!! allmost there, lets make sure those spammers dont get trought"

  & 'C:\Program Files\Microsoft\Exchange Server\V14\Scripts\install-AntispamAgents.ps1'
  Write-Host "Watch out!! I`m going to restart the transportservice, are ok with that???"
  Write-Host "just smash the keyboard if you are!!!!"
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  Restart-Service msexchangetransport

  #m$ always likes to give you toooooo much, so i need to disable some things.."
  Set-ContentFilterConfig -Enabled $false
  Set-IPAllowListConfig -enabled $false
  Set-IPblockListConfig -enabled $false
  Set-IPBlockListProvidersConfig -enabled $false
  Set-IPAllowListProvidersConfig -enabled $false
  Set-SenderFilterConfig -enabled $false
  Set-SenderIdConfig -enabled $false
  Set-SenderReputationConfig -enabled $false
  Set-RecipientFilterConfig -RecipientValidationEnabled $true

  # finalizing! lets get those systemlogs in the right place!
  Get-MailboxServer | Set-MailboxServer -MessageTrackingLogPath "f:\$companyname ExchangeSystem Logs\messagetrackinglog"
  Get-TransportServer | Set-TransportServer -ConnectivityLogPath "f:\$companyname ExchangeSystem Logs\connectivitylog"
  Get-TransportServer | Set-TransportServer -SendProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpSend"
  Get-TransportServer | Set-TransportServer -ReceiveProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpRecieve"
}

Function Start-Setup8 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
 
  $userou = "$companyname.local/ou$companyname/ouUsers/ouInternalUsers"
  $csvfile = "c:\scripts\users.csv"

  Import-CSV $CSVFile | ForEach-Object -Process {New-Mailbox -Name $_.Name -FirstName $_.FirstName -LastName $_.LastName -displayname $_.displayname -alias $_.alias  -UserPrincipalName $_.upn -organizationalunit "$userou" -Password $DefaultUserPassword | set-user -city $_.city -company $_.company -countryorregion $_.countryorregion -fax $_.fax -mobilephone $_.mobilephone -phone $_.phone -postalcode $_.postalcode -streetaddress $_.streetaddress -title $_.title}
}

#
# Main Code
#

If ($PsCmdLet.ParameterSetName -eq "AutoConfig") {

  # Load the settings if we're in autoconfig mode

  $Settings = Import-Csv $ConfigurationFile
  
  $CompanyName = $Settings.CompanyName
  $RestoreModePassword = $Settings.RestoreModePassword
  $AdministratorPassword = $Settings.AdministratorPassword
  $DefaultUserPassword = $Settings.DefaultUserPassword
  $MailDomain = $Settings.MailDomain
  $WebmailFQDN = $Settings.WebmailFQDN
  $ScriptStep = $Settings.ScriptStep

} Else {

  # Set the default configuration file location

  $ConfigurationFile = "settings.csv"

}

# Create / Rewrite the autoconfiguration file and increment the script step

New-Object PsObject -Property @{
  CompanyName = $CompanyName;
  RestoreModePassword = $RestoreModePassword;
  AdministratorPassword = $AdministratorPassword;
  DefaultUserPassword = $DefaultUserPassword;
  Maildomain = $MailDomain;
  WebmailFQDN = $WebmailFQDN;
  ScriptStep = ($ScriptStep + 1);
} | Export-Csv $ConfigurationFile

# Convert the passwords to secure strings

$SecureRestoreModePassword = $RestoreModePassword | ConvertTo-SecureString -AsPlainText -Force
$SecureAdministratorPassword = $AdministratorPassword | ConvertTo-SecureString -AsPlainText -Force

# Validate the certificate path

If (!(Test-Path "C:\Scripts\$WebmailFQDN.pfx")) {
  Write-Error "Certificate file does not exist. Aborting script."
  Break
}

# If this is the first time the script has been called it will run 1
# otherwise it will run each of the remaining steps in sequence

Switch ($ScriptStep) {
  1       {
    New-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript" `
      -Value "PowerShell.exe { C:\Scripts\setup.ps1 -ConfigurationFile $ConfigurationFile }"

    Start-Setup1
  }
  default {

    Start-Setup2
    Start-Setup3
    Start-Setup5
    Start-Setup7
    Start-Setup8


    # Clean up

    Remove-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript"
  }
}

Open in new window

that looks complex:) THANKS!.... but....

when i excute the script i`m getting this error:

C:\Scripts\huge.ps1 : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:20
+ C:\Scripts\huge.ps1 <<<<  : Parameter set cannot be resolved using the specified named parameters.
    + CategoryInfo          : InvalidArgument: (:) [huge.ps1], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,huge.ps1

that is both in your version and my edited version (one more variable and some things i left out)

We can make it yell about what's missing with this modification.

[CmdLetBinding(DefaultParameterSetName = "ManualConfig")]

We tell the script that it should use ManualConfig if it can't figure out the set from the parameters we're asking for (those set to Mandatory = $True for ManualConfig).

Chris
#Requires -version 2.0

<#
  .Synopsis
    This script performs initial setup of a domain controller
  .Description
    This script performs initial setup of a domain controller
  .Parameter CompanyName
    The company name
  .Parameter RestoreModePassword
    The password used when booting into Restore Mode
  .Parameter AdministratorPassword
    Set as the Active Directory Administrator password.
  .Parameter DefaultUserPassword
    The default password for user accounts created by this script.
  .Parameter MailDomain
    The e-mail domain name
  .Parameter WebmailFQDN
    Used in the URL to access web-mail and used to obtain the certificate
  .Parameter ConfigurationFile
    A CSV formatted file containing all required parameters.
  .Parameter ScriptStep
    Helps the script progress across reboot
#>

[CmdLetBinding(DefaultParameterSetName = "ManualConfig")]
Param(
  # Company Name
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$CompanyName,

  # Restore Mode (Safe Mode) password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$RestoreModePassword,

  # Administrator password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$AdministratorPassword,

  # Default user passsword
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$DefaultUserPassword,

  # Mail Domain
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$MailDomain,

  # Webmail FQDN
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$WebmailFQDN,

  # Automatic configuration (from file)
  [Parameter(Mandatory = $True, ParameterSetName = "AutoConfig")]
  [ValidateScript( { Test-Path $_ } )]
  [String]$ConfigurationFile,

  # Script Step
  [Parameter(ParameterSetName = "")]
  [Int32]$ScriptStep = 1
)

#
# Functions
#

Function Start-Setup1 {

  #This is the first script you can run after the creation of a new domaincontroller.
  #First installation of some features
  Import-Module servermanager
  Add-WindowsFeature telnet-client, Backup-features

  #Now lets format some drives which weren't in the setup.
  Write-host "WARNING DRIVES D:/E:/F: will be formated"
  write-host "Formating D: drive starts now."
  Start-Sleep -s 1
  format d: /fs:NTFS /v:Data /Q
  write-host "Formating E: drive starts now."
  Start-Sleep -s 1
  format e: /fs:NTFS /v:MDB /Q
  write-host "Formating F: drive starts now."
  Start-Sleep -s 1
  format f: /fs:NTFS /v:LOG /Q

  #Now lets change the computername.
  $servername = "$($CompanyName)DC01"

  write-host "this servername will be used: $servername"
  Start-Sleep -s 1

  $oComputerSystem = Get-WmiObject win32_computersystem
  $oComputerSystem.Rename( "$servername" )

  write-host "I`m done, let me reboot the server for you."
  Start-Sleep -s 1
  write-host "Rebooting"
  start-sleep -s 1
  shutdown /r /t 0

}

Function Start-Setup2 {

  # This script installs and configures a new AD on this server. It assumes that this is a complete new forest.
  # First we install the necessary roles.

  Write-Host "Installing the necessary roles"
  import-module servermanager
  add-windowsfeature ad-domain-services

  Write-Host "ok everything went well!, now I need to know somethings!"
  Start-Sleep 2
  $domaindnsname = "$CompanyName.local"
  Write-Host "thanks, so the domainname will be $domaindnsname is that correct?"
  Write-Host "Press any key to continue ..."
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  Write-Host "Thanks now i have everything i need, dont worry i`ll install a dns server for you!"

  dcpromo /unattend /installdns=yes /newdomain=forest /newdomaindnsname=$domaindnsname /domainnetbiosname=$CompanyName /ReplicaOrNewDomain=domain /forestlevel=4 /domainlevel=4 /rebootoncompletion=yes /safemodeadminpassword=$RestorModePassword

}

Function Start-Setup3 {

  #This script installs features, sets windows update, creates the standard OU structure, creates the admin accounts, data folders, shares and the correct ACL`s
  #This script should also test to see if active directory snap-in is loaded, but currently i dont know how to do that!
  #Importing activedirectory module!

  Import-Module ActiveDirectory

  #change windows update settings
  cscript.exe c:\scripts\windowsupdate.vbs

  #Create new Organizational units.

  New-ADOrganizationalUnit -Name ou$Companyname -Path "DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouComputers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouGroups -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouUsers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouLaptops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDesktops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouRDServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDomainControllers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAppServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDistribution -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSecurity -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Apps -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Shares -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Mailbox -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name "Start Menu" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouInternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouExternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouMailOnlyUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouContacts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSaAccounts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAdministrators -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false

  #Create new Security Groups
  New-ADGroup -Name "grRDUsers" -SamAccountName grRDUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers"
  New-ADGroup -Name "grRDHomeUsers" -SamAccountName grRDHomeUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop Home users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers from external locations"
  New-ADGroup -Name "grSharedData" -SamAccountName grSharedData -GroupCategory Security -GroupScope Global -DisplayName "Shared Data users " -Path "ou=Shares,ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group have access to the Company`s Shared data"

  #Create admin user accounts
  New-ADUser -Name "admxxx" -samaccountname xxxx -givenname "xxxx" -surname "xxxxx" -displayname "Adm xxxx" -path "ou=ouAdministrators,ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -Enabled $true -AccountPassword $AdministratorPassword -ChangePasswordAtLogon $true

  #Add admin accounts to the administrators group
  add-adgroupmember Administrators xxx

  #Now we are going to create the data, profile and user home directies.
  new-item d:\"$companyname Data" -type directory
  new-item d:\"$companyname Data"\"Shared_Data" -type directory
  new-item d:\"$companyname Data"\"RDProfiles" -type directory
  new-item d:\"$companyname Data"\"Profiles" -type directory
  new-item d:\"$companyname Data"\"Home" -type directory

  net share "Shared_Data$=d:\$companyname Data\Shared_Data" "/grant:everyone,full"
  net share "RDProfiles$=d:\$companyname Data\RDProfiles" "/grant:everyone,full"
  net share "Profiles$=d:\$companyname Data\Profiles" "/grant:everyone,full"
  net share "Home$=d:\$companyname Data\Home" "/grant:everyone,full"

  icacls "d:\$companyname data" /inheritance:d
  icacls "d:\$companyname data" /remove:g users
  icacls "d:\$companyname Data\Shared_Data" /grant:r grSharedData:"(OI)(CI)M"
  icacls "d:\$companyname Data\RDProfiles" /grant:r users:rd
  icacls "d:\$companyname Data\Profiles" /grant:r users:rd
  icacls "d:\$companyname Data\Home" /grant:r users:rd

}

Function Start-Setup5 {

  Write-host "this script installs exchange"
  Write-host "with the following roles: CAS/HUB/Mailbox"
  write-host "This script assumes that you have got 4 drives:"
  write-host " c: (system) d:(Data) e:(MDB) f:(log)"
  write-host "Press any key to continue ..."
  $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  new-item E:\"$companyname Exchange MDBs" -type directory
  new-item F:\"$companyname Exchange Logs" -type directory
  new-item E:\"$companyname Exchange MDBs"\"Mailbox" -type directory
  new-item E:\"$companyname Exchange MDBs"\"PublicFolder" -type directory
  new-item F:\"$companyname Exchange Logs"\"Mailbox" -type directory
  new-item F:\"$companyname Exchange Logs"\"PublicFolder" -type directory
  new-item F:\"$companyname ExchangeSystem Logs" -type directory

  $mdbpath = "E:\$companyname Exchange MDBs\Mailbox\$companyname.edb"
  $logpath = "E:\$companyname Exchange Logs\Mailbox"
  $mdbname = "$Companyname MailboxDB"

  Set-Service NetTcpPortSharing -StartupType Automatic

  G:\setup.com /mode:install /roles:"mb,ht,ca" /mdbname:$mdbname /dbfilepath:$mdbpath /logfolderpath:$logpath /organizationname:$Companyname
}

Function Start-Setup7 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
  #Lets get some variables

  $sendconnectorname = "$Companyname Sendconnector"

  #remove the limitations for messages and mailbox size on the mailbox store.
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendReceiveQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -IssueWarningQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendQuota unlimited

  #set the deleteditemretention to 30 days.
  Get-MailboxDatabase | set-mailboxdatabase -DeletedItemRetention 30

  #enabling circularlogging
  Get-MailboxDatabase | set-mailboxdatabase -CircularLoggingEnabled 1

  #lets make a sendconnector
  new-sendconnector -name $sendconnectorname -addressspace * -fqdn $WebmailFQDN -smarthosts mx1.blaaat.com -maxmessagesize 20480

  #next we make a new accepteddomain
  
  new-accepteddomain $companyname -domaintype authoritative -domainname $MailDomain
  set-accepteddomain $companyname -makedefault $true

  #ok time to set the right emailaddresspolicy
  get-emailaddresspolicy | set-emailaddresspolicy -enabledprimarysmtpaddresstemplate "smtp:%m@$MailDomain"

  #now we want to recieve mail from the outside so we need to add anonymoususers to the right recieveconnector
  Get-ReceiveConnector | where {$_.identity -like "*Default*"} | Set-ReceiveConnector -PermissionGroups anonymoususers,exchangeusers,exchangeservers,exchangelegacyservers -MaxMessageSize 20mb

  #owa rules so no need to wait any longer to enable it!
  Enable-OutlookAnywhere -ExternalHostname $externalurl -SSLOffloading $false -DefaultAuthenticationMethod 'Basic'

  Import-ExchangeCertificate -FileData ([Byte[]]$(Get-Content -Path "c:\scripts\$WebmailFQDN.pfx" -Encoding byte -ReadCount 0)) -Password:$certpass
  get-exchangecertificate | where {$_.subject -like "*$WebmailFQDN*"} | enable-exchangecertificate -service imap,pop,smtp,iis -force

  #OK!!! allmost there, lets make sure those spammers dont get trought"

  & 'C:\Program Files\Microsoft\Exchange Server\V14\Scripts\install-AntispamAgents.ps1'
  Write-Host "Watch out!! I`m going to restart the transportservice, are ok with that???"
  Write-Host "just smash the keyboard if you are!!!!"
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  Restart-Service msexchangetransport

  #m$ always likes to give you toooooo much, so i need to disable some things.."
  Set-ContentFilterConfig -Enabled $false
  Set-IPAllowListConfig -enabled $false
  Set-IPblockListConfig -enabled $false
  Set-IPBlockListProvidersConfig -enabled $false
  Set-IPAllowListProvidersConfig -enabled $false
  Set-SenderFilterConfig -enabled $false
  Set-SenderIdConfig -enabled $false
  Set-SenderReputationConfig -enabled $false
  Set-RecipientFilterConfig -RecipientValidationEnabled $true

  # finalizing! lets get those systemlogs in the right place!
  Get-MailboxServer | Set-MailboxServer -MessageTrackingLogPath "f:\$companyname ExchangeSystem Logs\messagetrackinglog"
  Get-TransportServer | Set-TransportServer -ConnectivityLogPath "f:\$companyname ExchangeSystem Logs\connectivitylog"
  Get-TransportServer | Set-TransportServer -SendProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpSend"
  Get-TransportServer | Set-TransportServer -ReceiveProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpRecieve"
}

Function Start-Setup8 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
 
  $userou = "$companyname.local/ou$companyname/ouUsers/ouInternalUsers"
  $csvfile = "c:\scripts\users.csv"

  Import-CSV $CSVFile | ForEach-Object -Process {New-Mailbox -Name $_.Name -FirstName $_.FirstName -LastName $_.LastName -displayname $_.displayname -alias $_.alias  -UserPrincipalName $_.upn -organizationalunit "$userou" -Password $DefaultUserPassword | set-user -city $_.city -company $_.company -countryorregion $_.countryorregion -fax $_.fax -mobilephone $_.mobilephone -phone $_.phone -postalcode $_.postalcode -streetaddress $_.streetaddress -title $_.title}
}

#
# Main Code
#

If ($PsCmdLet.ParameterSetName -eq "AutoConfig") {

  # Load the settings if we're in autoconfig mode

  $Settings = Import-Csv $ConfigurationFile
  
  $CompanyName = $Settings.CompanyName
  $RestoreModePassword = $Settings.RestoreModePassword
  $AdministratorPassword = $Settings.AdministratorPassword
  $DefaultUserPassword = $Settings.DefaultUserPassword
  $MailDomain = $Settings.MailDomain
  $WebmailFQDN = $Settings.WebmailFQDN
  $ScriptStep = $Settings.ScriptStep

} Else {

  # Set the default configuration file location

  $ConfigurationFile = "settings.csv"

}

# Create / Rewrite the autoconfiguration file and increment the script step

New-Object PsObject -Property @{
  CompanyName = $CompanyName;
  RestoreModePassword = $RestoreModePassword;
  AdministratorPassword = $AdministratorPassword;
  DefaultUserPassword = $DefaultUserPassword;
  Maildomain = $MailDomain;
  WebmailFQDN = $WebmailFQDN;
  ScriptStep = ($ScriptStep + 1);
} | Export-Csv $ConfigurationFile

# Convert the passwords to secure strings

$SecureRestoreModePassword = $RestoreModePassword | ConvertTo-SecureString -AsPlainText -Force
$SecureAdministratorPassword = $AdministratorPassword | ConvertTo-SecureString -AsPlainText -Force

# Validate the certificate path

If (!(Test-Path "C:\Scripts\$WebmailFQDN.pfx")) {
  Write-Error "Certificate file does not exist. Aborting script."
  Break
}

# If this is the first time the script has been called it will run 1
# otherwise it will run each of the remaining steps in sequence

Switch ($ScriptStep) {
  1       {
    New-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript" `
      -Value "PowerShell.exe { C:\Scripts\setup.ps1 -ConfigurationFile $ConfigurationFile }"

    Start-Setup1
  }
  default {

    Start-Setup2
    Start-Setup3
    Start-Setup5
    Start-Setup7
    Start-Setup8


    # Clean up

    Remove-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript"
  }
}

Open in new window

thanks!!

It runs the first step of the script now, but it doenst go any futher after the reboot.
In the registry is the right entry in "run"
PowerShell.exe { C:\Scripts\huge.ps1 -ConfigurationFile settings.csv }
the csv file is present and also the scriptstep is 2!?

I changed the script a little so this is the beginning of step 2

function Start-Setup2 {

  Write-Host "Do you want to continue with step 2 of the script?"
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
 
  # This script installs and configures a new AD on this server. It assumes that this is a complete new forest.
  # First we install the necessary roles.

that shouldnt be the problem right? or doenst it run the script interactivaly anymore?

Couple of changes then. First lets make the script run under the user context (HKCU). And lets make the PS window stay open (if we can).

I've changed HKLM to HKCU below, and added the NoExit parameter to the entry it writes to the registry.

Chris
#Requires -version 2.0

<#
  .Synopsis
    This script performs initial setup of a domain controller
  .Description
    This script performs initial setup of a domain controller
  .Parameter CompanyName
    The company name
  .Parameter RestoreModePassword
    The password used when booting into Restore Mode
  .Parameter AdministratorPassword
    Set as the Active Directory Administrator password.
  .Parameter DefaultUserPassword
    The default password for user accounts created by this script.
  .Parameter MailDomain
    The e-mail domain name
  .Parameter WebmailFQDN
    Used in the URL to access web-mail and used to obtain the certificate
  .Parameter ConfigurationFile
    A CSV formatted file containing all required parameters.
  .Parameter ScriptStep
    Helps the script progress across reboot
#>

[CmdLetBinding(DefaultParameterSetName = "ManualConfig")]
Param(
  # Company Name
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$CompanyName,

  # Restore Mode (Safe Mode) password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$RestoreModePassword,

  # Administrator password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$AdministratorPassword,

  # Default user passsword
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$DefaultUserPassword,

  # Mail Domain
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$MailDomain,

  # Webmail FQDN
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$WebmailFQDN,

  # Automatic configuration (from file)
  [Parameter(Mandatory = $True, ParameterSetName = "AutoConfig")]
  [ValidateScript( { Test-Path $_ } )]
  [String]$ConfigurationFile,

  # Script Step
  [Parameter(ParameterSetName = "")]
  [Int32]$ScriptStep = 1
)

#
# Functions
#

Function Start-Setup1 {

  #This is the first script you can run after the creation of a new domaincontroller.
  #First installation of some features
  Import-Module servermanager
  Add-WindowsFeature telnet-client, Backup-features

  #Now lets format some drives which weren't in the setup.
  Write-host "WARNING DRIVES D:/E:/F: will be formated"
  write-host "Formating D: drive starts now."
  Start-Sleep -s 1
  format d: /fs:NTFS /v:Data /Q
  write-host "Formating E: drive starts now."
  Start-Sleep -s 1
  format e: /fs:NTFS /v:MDB /Q
  write-host "Formating F: drive starts now."
  Start-Sleep -s 1
  format f: /fs:NTFS /v:LOG /Q

  #Now lets change the computername.
  $servername = "$($CompanyName)DC01"

  write-host "this servername will be used: $servername"
  Start-Sleep -s 1

  $oComputerSystem = Get-WmiObject win32_computersystem
  $oComputerSystem.Rename( "$servername" )

  write-host "I`m done, let me reboot the server for you."
  Start-Sleep -s 1
  write-host "Rebooting"
  start-sleep -s 1
  shutdown /r /t 0

}

Function Start-Setup2 {

  # This script installs and configures a new AD on this server. It assumes that this is a complete new forest.
  # First we install the necessary roles.

  Write-Host "Installing the necessary roles"
  import-module servermanager
  add-windowsfeature ad-domain-services

  Write-Host "ok everything went well!, now I need to know somethings!"
  Start-Sleep 2
  $domaindnsname = "$CompanyName.local"
  Write-Host "thanks, so the domainname will be $domaindnsname is that correct?"
  Write-Host "Press any key to continue ..."
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  Write-Host "Thanks now i have everything i need, dont worry i`ll install a dns server for you!"

  dcpromo /unattend /installdns=yes /newdomain=forest /newdomaindnsname=$domaindnsname /domainnetbiosname=$CompanyName /ReplicaOrNewDomain=domain /forestlevel=4 /domainlevel=4 /rebootoncompletion=yes /safemodeadminpassword=$RestorModePassword

}

Function Start-Setup3 {

  #This script installs features, sets windows update, creates the standard OU structure, creates the admin accounts, data folders, shares and the correct ACL`s
  #This script should also test to see if active directory snap-in is loaded, but currently i dont know how to do that!
  #Importing activedirectory module!

  Import-Module ActiveDirectory

  #change windows update settings
  cscript.exe c:\scripts\windowsupdate.vbs

  #Create new Organizational units.

  New-ADOrganizationalUnit -Name ou$Companyname -Path "DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouComputers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouGroups -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouUsers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouLaptops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDesktops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouRDServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDomainControllers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAppServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDistribution -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSecurity -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Apps -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Shares -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Mailbox -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name "Start Menu" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouInternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouExternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouMailOnlyUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouContacts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSaAccounts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAdministrators -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false

  #Create new Security Groups
  New-ADGroup -Name "grRDUsers" -SamAccountName grRDUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers"
  New-ADGroup -Name "grRDHomeUsers" -SamAccountName grRDHomeUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop Home users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers from external locations"
  New-ADGroup -Name "grSharedData" -SamAccountName grSharedData -GroupCategory Security -GroupScope Global -DisplayName "Shared Data users " -Path "ou=Shares,ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group have access to the Company`s Shared data"

  #Create admin user accounts
  New-ADUser -Name "admxxx" -samaccountname xxxx -givenname "xxxx" -surname "xxxxx" -displayname "Adm xxxx" -path "ou=ouAdministrators,ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -Enabled $true -AccountPassword $AdministratorPassword -ChangePasswordAtLogon $true

  #Add admin accounts to the administrators group
  add-adgroupmember Administrators xxx

  #Now we are going to create the data, profile and user home directies.
  new-item d:\"$companyname Data" -type directory
  new-item d:\"$companyname Data"\"Shared_Data" -type directory
  new-item d:\"$companyname Data"\"RDProfiles" -type directory
  new-item d:\"$companyname Data"\"Profiles" -type directory
  new-item d:\"$companyname Data"\"Home" -type directory

  net share "Shared_Data$=d:\$companyname Data\Shared_Data" "/grant:everyone,full"
  net share "RDProfiles$=d:\$companyname Data\RDProfiles" "/grant:everyone,full"
  net share "Profiles$=d:\$companyname Data\Profiles" "/grant:everyone,full"
  net share "Home$=d:\$companyname Data\Home" "/grant:everyone,full"

  icacls "d:\$companyname data" /inheritance:d
  icacls "d:\$companyname data" /remove:g users
  icacls "d:\$companyname Data\Shared_Data" /grant:r grSharedData:"(OI)(CI)M"
  icacls "d:\$companyname Data\RDProfiles" /grant:r users:rd
  icacls "d:\$companyname Data\Profiles" /grant:r users:rd
  icacls "d:\$companyname Data\Home" /grant:r users:rd

}

Function Start-Setup5 {

  Write-host "this script installs exchange"
  Write-host "with the following roles: CAS/HUB/Mailbox"
  write-host "This script assumes that you have got 4 drives:"
  write-host " c: (system) d:(Data) e:(MDB) f:(log)"
  write-host "Press any key to continue ..."
  $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  new-item E:\"$companyname Exchange MDBs" -type directory
  new-item F:\"$companyname Exchange Logs" -type directory
  new-item E:\"$companyname Exchange MDBs"\"Mailbox" -type directory
  new-item E:\"$companyname Exchange MDBs"\"PublicFolder" -type directory
  new-item F:\"$companyname Exchange Logs"\"Mailbox" -type directory
  new-item F:\"$companyname Exchange Logs"\"PublicFolder" -type directory
  new-item F:\"$companyname ExchangeSystem Logs" -type directory

  $mdbpath = "E:\$companyname Exchange MDBs\Mailbox\$companyname.edb"
  $logpath = "E:\$companyname Exchange Logs\Mailbox"
  $mdbname = "$Companyname MailboxDB"

  Set-Service NetTcpPortSharing -StartupType Automatic

  G:\setup.com /mode:install /roles:"mb,ht,ca" /mdbname:$mdbname /dbfilepath:$mdbpath /logfolderpath:$logpath /organizationname:$Companyname
}

Function Start-Setup7 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
  #Lets get some variables

  $sendconnectorname = "$Companyname Sendconnector"

  #remove the limitations for messages and mailbox size on the mailbox store.
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendReceiveQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -IssueWarningQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendQuota unlimited

  #set the deleteditemretention to 30 days.
  Get-MailboxDatabase | set-mailboxdatabase -DeletedItemRetention 30

  #enabling circularlogging
  Get-MailboxDatabase | set-mailboxdatabase -CircularLoggingEnabled 1

  #lets make a sendconnector
  new-sendconnector -name $sendconnectorname -addressspace * -fqdn $WebmailFQDN -smarthosts mx1.blaaat.com -maxmessagesize 20480

  #next we make a new accepteddomain
  
  new-accepteddomain $companyname -domaintype authoritative -domainname $MailDomain
  set-accepteddomain $companyname -makedefault $true

  #ok time to set the right emailaddresspolicy
  get-emailaddresspolicy | set-emailaddresspolicy -enabledprimarysmtpaddresstemplate "smtp:%m@$MailDomain"

  #now we want to recieve mail from the outside so we need to add anonymoususers to the right recieveconnector
  Get-ReceiveConnector | where {$_.identity -like "*Default*"} | Set-ReceiveConnector -PermissionGroups anonymoususers,exchangeusers,exchangeservers,exchangelegacyservers -MaxMessageSize 20mb

  #owa rules so no need to wait any longer to enable it!
  Enable-OutlookAnywhere -ExternalHostname $externalurl -SSLOffloading $false -DefaultAuthenticationMethod 'Basic'

  Import-ExchangeCertificate -FileData ([Byte[]]$(Get-Content -Path "c:\scripts\$WebmailFQDN.pfx" -Encoding byte -ReadCount 0)) -Password:$certpass
  get-exchangecertificate | where {$_.subject -like "*$WebmailFQDN*"} | enable-exchangecertificate -service imap,pop,smtp,iis -force

  #OK!!! allmost there, lets make sure those spammers dont get trought"

  & 'C:\Program Files\Microsoft\Exchange Server\V14\Scripts\install-AntispamAgents.ps1'
  Write-Host "Watch out!! I`m going to restart the transportservice, are ok with that???"
  Write-Host "just smash the keyboard if you are!!!!"
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  Restart-Service msexchangetransport

  #m$ always likes to give you toooooo much, so i need to disable some things.."
  Set-ContentFilterConfig -Enabled $false
  Set-IPAllowListConfig -enabled $false
  Set-IPblockListConfig -enabled $false
  Set-IPBlockListProvidersConfig -enabled $false
  Set-IPAllowListProvidersConfig -enabled $false
  Set-SenderFilterConfig -enabled $false
  Set-SenderIdConfig -enabled $false
  Set-SenderReputationConfig -enabled $false
  Set-RecipientFilterConfig -RecipientValidationEnabled $true

  # finalizing! lets get those systemlogs in the right place!
  Get-MailboxServer | Set-MailboxServer -MessageTrackingLogPath "f:\$companyname ExchangeSystem Logs\messagetrackinglog"
  Get-TransportServer | Set-TransportServer -ConnectivityLogPath "f:\$companyname ExchangeSystem Logs\connectivitylog"
  Get-TransportServer | Set-TransportServer -SendProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpSend"
  Get-TransportServer | Set-TransportServer -ReceiveProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpRecieve"
}

Function Start-Setup8 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
 
  $userou = "$companyname.local/ou$companyname/ouUsers/ouInternalUsers"
  $csvfile = "c:\scripts\users.csv"

  Import-CSV $CSVFile | ForEach-Object -Process {New-Mailbox -Name $_.Name -FirstName $_.FirstName -LastName $_.LastName -displayname $_.displayname -alias $_.alias  -UserPrincipalName $_.upn -organizationalunit "$userou" -Password $DefaultUserPassword | set-user -city $_.city -company $_.company -countryorregion $_.countryorregion -fax $_.fax -mobilephone $_.mobilephone -phone $_.phone -postalcode $_.postalcode -streetaddress $_.streetaddress -title $_.title}
}

#
# Main Code
#

If ($PsCmdLet.ParameterSetName -eq "AutoConfig") {

  # Load the settings if we're in autoconfig mode

  $Settings = Import-Csv $ConfigurationFile
  
  $CompanyName = $Settings.CompanyName
  $RestoreModePassword = $Settings.RestoreModePassword
  $AdministratorPassword = $Settings.AdministratorPassword
  $DefaultUserPassword = $Settings.DefaultUserPassword
  $MailDomain = $Settings.MailDomain
  $WebmailFQDN = $Settings.WebmailFQDN
  $ScriptStep = $Settings.ScriptStep

} Else {

  # Set the default configuration file location

  $ConfigurationFile = "settings.csv"

}

# Create / Rewrite the autoconfiguration file and increment the script step

New-Object PsObject -Property @{
  CompanyName = $CompanyName;
  RestoreModePassword = $RestoreModePassword;
  AdministratorPassword = $AdministratorPassword;
  DefaultUserPassword = $DefaultUserPassword;
  Maildomain = $MailDomain;
  WebmailFQDN = $WebmailFQDN;
  ScriptStep = ($ScriptStep + 1);
} | Export-Csv $ConfigurationFile

# Convert the passwords to secure strings

$SecureRestoreModePassword = $RestoreModePassword | ConvertTo-SecureString -AsPlainText -Force
$SecureAdministratorPassword = $AdministratorPassword | ConvertTo-SecureString -AsPlainText -Force

# Validate the certificate path

If (!(Test-Path "C:\Scripts\$WebmailFQDN.pfx")) {
  Write-Error "Certificate file does not exist. Aborting script."
  Break
}

# If this is the first time the script has been called it will run 1
# otherwise it will run each of the remaining steps in sequence

Switch ($ScriptStep) {
  1       {
    New-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript" `
      -Value "PowerShell.exe { C:\Scripts\setup.ps1 -ConfigurationFile $ConfigurationFile } -NoExit"

    Start-Setup1
  }
  default {

    Start-Setup2
    Start-Setup3
    Start-Setup5
    Start-Setup7
    Start-Setup8


    # Clean up

    Remove-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript"
  }
}

Open in new window

nope still same problem, but also if we put it in HKCU, what will happen if the server is changed to a domain controller? IT is still the same useraccount so maybe it wont be a problem...


Shouldn't matter, HKCU is based on NTUser.dat, so as long as the profile loads :)

Anyway, are we able to see if it even starts the task?

Otherwise, can you copy out the entry from the Run key, then paste it into the Run box? See if it starts properly. We may setting it up as a scheduled task instead (scheduled to run at startup).

Chris
manually it gives an error:

PS C:\Users\Administrator> PowerShell.exe { C:\Scripts\huge.ps1 -ConfigurationFile settings.csv } -NoExit
C:\Scripts\huge.ps1 : Cannot validate argument on parameter 'ConfigurationFile'. The " Test-Path $_ " validation script
 for the argument with value "settings.csv" did not return true. Determine why the validation script failed and then tr
y the command again.
At line:1 char:40
+  C:\Scripts\huge.ps1 -ConfigurationFile <<<<  settings.csv
    + CategoryInfo          : InvalidData: (:) [huge.ps1], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,huge.ps1


  # Automatic configuration (from file)
  [Parameter(Mandatory = $True, ParameterSetName = "AutoConfig")]
  [ValidateScript( { Test-Path $_ } )]
  [String]$ConfigurationFile,

sorry i lost it.... dont know what this statement is trying to do.

Ah ha... can we try this?

Modified this line:

  $ConfigurationFile = "c:\scripts\settings.csv"

The error above was a result of it checking the configuration file path. And that was only "settings.csv", a relative path rather than an absolute path.

Chris
ok so copying this PowerShell.exe { C:\Scripts\huge.ps1 -ConfigurationFile c:\scripts\settings.csv } -NoExit into a "run" doenst work, but opening an powershell screen an copying it into the screen works!

Btw through run powershell starts but shuts again after 10 sec orso..

So much for NoExit.

Would you start up a regular command prompt and paste it in there?

Chris
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Administrator>PowerShell.exe { C:\Scripts\huge.ps1 -ConfigurationFile c
:\scripts\settings.csv } -NoExit
You must provide a value expression on the right-hand side of the '-' operator.
At line:1 char:69
+ { C:\Scripts\huge.ps1 -ConfigurationFile c:\scripts\settings.csv } - <<<< NoE
xit
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : ExpectedValueExpression


C:\Users\Administrator>


I think I've just seen what I missed out. Would you try:

PowerShell.exe  -NoExit -Command "C:\Scripts\huge.ps1 -ConfigurationFile c:\scripts\settings.csv"

And if that works, this modification might help.

Chris
#Requires -version 2.0

<#
  .Synopsis
    This script performs initial setup of a domain controller
  .Description
    This script performs initial setup of a domain controller
  .Parameter CompanyName
    The company name
  .Parameter RestoreModePassword
    The password used when booting into Restore Mode
  .Parameter AdministratorPassword
    Set as the Active Directory Administrator password.
  .Parameter DefaultUserPassword
    The default password for user accounts created by this script.
  .Parameter MailDomain
    The e-mail domain name
  .Parameter WebmailFQDN
    Used in the URL to access web-mail and used to obtain the certificate
  .Parameter ConfigurationFile
    A CSV formatted file containing all required parameters.
  .Parameter ScriptStep
    Helps the script progress across reboot
#>

[CmdLetBinding(DefaultParameterSetName = "ManualConfig")]
Param(
  # Company Name
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$CompanyName,

  # Restore Mode (Safe Mode) password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$RestoreModePassword,

  # Administrator password
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$AdministratorPassword,

  # Default user passsword
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$DefaultUserPassword,

  # Mail Domain
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$MailDomain,

  # Webmail FQDN
  [Parameter(Mandatory = $True, ParameterSetName = "ManualConfig")]
  [String]$WebmailFQDN,

  # Automatic configuration (from file)
  [Parameter(Mandatory = $True, ParameterSetName = "AutoConfig")]
  [ValidateScript( { Test-Path $_ } )]
  [String]$ConfigurationFile,

  # Script Step
  [Parameter(ParameterSetName = "")]
  [Int32]$ScriptStep = 1
)

#
# Functions
#

Function Start-Setup1 {

  #This is the first script you can run after the creation of a new domaincontroller.
  #First installation of some features
  Import-Module servermanager
  Add-WindowsFeature telnet-client, Backup-features

  #Now lets format some drives which weren't in the setup.
  Write-host "WARNING DRIVES D:/E:/F: will be formated"
  write-host "Formating D: drive starts now."
  Start-Sleep -s 1
  format d: /fs:NTFS /v:Data /Q
  write-host "Formating E: drive starts now."
  Start-Sleep -s 1
  format e: /fs:NTFS /v:MDB /Q
  write-host "Formating F: drive starts now."
  Start-Sleep -s 1
  format f: /fs:NTFS /v:LOG /Q

  #Now lets change the computername.
  $servername = "$($CompanyName)DC01"

  write-host "this servername will be used: $servername"
  Start-Sleep -s 1

  $oComputerSystem = Get-WmiObject win32_computersystem
  $oComputerSystem.Rename( "$servername" )

  write-host "I`m done, let me reboot the server for you."
  Start-Sleep -s 1
  write-host "Rebooting"
  start-sleep -s 1
  shutdown /r /t 0

}

Function Start-Setup2 {

  # This script installs and configures a new AD on this server. It assumes that this is a complete new forest.
  # First we install the necessary roles.

  Write-Host "Installing the necessary roles"
  import-module servermanager
  add-windowsfeature ad-domain-services

  Write-Host "ok everything went well!, now I need to know somethings!"
  Start-Sleep 2
  $domaindnsname = "$CompanyName.local"
  Write-Host "thanks, so the domainname will be $domaindnsname is that correct?"
  Write-Host "Press any key to continue ..."
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  Write-Host "Thanks now i have everything i need, dont worry i`ll install a dns server for you!"

  dcpromo /unattend /installdns=yes /newdomain=forest /newdomaindnsname=$domaindnsname /domainnetbiosname=$CompanyName /ReplicaOrNewDomain=domain /forestlevel=4 /domainlevel=4 /rebootoncompletion=yes /safemodeadminpassword=$RestorModePassword

}

Function Start-Setup3 {

  #This script installs features, sets windows update, creates the standard OU structure, creates the admin accounts, data folders, shares and the correct ACL`s
  #This script should also test to see if active directory snap-in is loaded, but currently i dont know how to do that!
  #Importing activedirectory module!

  Import-Module ActiveDirectory

  #change windows update settings
  cscript.exe c:\scripts\windowsupdate.vbs

  #Create new Organizational units.

  New-ADOrganizationalUnit -Name ou$Companyname -Path "DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouComputers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouGroups -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouUsers -Path "ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouLaptops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDesktops -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouRDServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDomainControllers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAppServers -Path "ou=ouComputers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouDistribution -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSecurity -Path "ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Apps -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Shares -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name Mailbox -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name "Start Menu" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouInternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouExternalUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouMailOnlyUsers -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouContacts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouSaAccounts -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false
  New-ADOrganizationalUnit -Name ouAdministrators -Path "ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -ProtectedFromAccidentalDeletion $false

  #Create new Security Groups
  New-ADGroup -Name "grRDUsers" -SamAccountName grRDUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers"
  New-ADGroup -Name "grRDHomeUsers" -SamAccountName grRDHomeUsers -GroupCategory Security -GroupScope Global -DisplayName "Remote Desktop Home users" -Path "ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group can login on RD Servers from external locations"
  New-ADGroup -Name "grSharedData" -SamAccountName grSharedData -GroupCategory Security -GroupScope Global -DisplayName "Shared Data users " -Path "ou=Shares,ou=ouSecurity,ou=ouGroups,ou=ou$Companyname,DC=$Companyname,DC=local" -Description "Members of this group have access to the Company`s Shared data"

  #Create admin user accounts
  New-ADUser -Name "admxxx" -samaccountname xxxx -givenname "xxxx" -surname "xxxxx" -displayname "Adm xxxx" -path "ou=ouAdministrators,ou=ouUsers,ou=ou$Companyname,DC=$Companyname,DC=local" -Enabled $true -AccountPassword $AdministratorPassword -ChangePasswordAtLogon $true

  #Add admin accounts to the administrators group
  add-adgroupmember Administrators xxx

  #Now we are going to create the data, profile and user home directies.
  new-item d:\"$companyname Data" -type directory
  new-item d:\"$companyname Data"\"Shared_Data" -type directory
  new-item d:\"$companyname Data"\"RDProfiles" -type directory
  new-item d:\"$companyname Data"\"Profiles" -type directory
  new-item d:\"$companyname Data"\"Home" -type directory

  net share "Shared_Data$=d:\$companyname Data\Shared_Data" "/grant:everyone,full"
  net share "RDProfiles$=d:\$companyname Data\RDProfiles" "/grant:everyone,full"
  net share "Profiles$=d:\$companyname Data\Profiles" "/grant:everyone,full"
  net share "Home$=d:\$companyname Data\Home" "/grant:everyone,full"

  icacls "d:\$companyname data" /inheritance:d
  icacls "d:\$companyname data" /remove:g users
  icacls "d:\$companyname Data\Shared_Data" /grant:r grSharedData:"(OI)(CI)M"
  icacls "d:\$companyname Data\RDProfiles" /grant:r users:rd
  icacls "d:\$companyname Data\Profiles" /grant:r users:rd
  icacls "d:\$companyname Data\Home" /grant:r users:rd

}

Function Start-Setup5 {

  Write-host "this script installs exchange"
  Write-host "with the following roles: CAS/HUB/Mailbox"
  write-host "This script assumes that you have got 4 drives:"
  write-host " c: (system) d:(Data) e:(MDB) f:(log)"
  write-host "Press any key to continue ..."
  $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  new-item E:\"$companyname Exchange MDBs" -type directory
  new-item F:\"$companyname Exchange Logs" -type directory
  new-item E:\"$companyname Exchange MDBs"\"Mailbox" -type directory
  new-item E:\"$companyname Exchange MDBs"\"PublicFolder" -type directory
  new-item F:\"$companyname Exchange Logs"\"Mailbox" -type directory
  new-item F:\"$companyname Exchange Logs"\"PublicFolder" -type directory
  new-item F:\"$companyname ExchangeSystem Logs" -type directory

  $mdbpath = "E:\$companyname Exchange MDBs\Mailbox\$companyname.edb"
  $logpath = "E:\$companyname Exchange Logs\Mailbox"
  $mdbname = "$Companyname MailboxDB"

  Set-Service NetTcpPortSharing -StartupType Automatic

  G:\setup.com /mode:install /roles:"mb,ht,ca" /mdbname:$mdbname /dbfilepath:$mdbpath /logfolderpath:$logpath /organizationname:$Companyname
}

Function Start-Setup7 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
  #Lets get some variables

  $sendconnectorname = "$Companyname Sendconnector"

  #remove the limitations for messages and mailbox size on the mailbox store.
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendReceiveQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -IssueWarningQuota unlimited
  Get-MailboxDatabase | set-mailboxdatabase -ProhibitSendQuota unlimited

  #set the deleteditemretention to 30 days.
  Get-MailboxDatabase | set-mailboxdatabase -DeletedItemRetention 30

  #enabling circularlogging
  Get-MailboxDatabase | set-mailboxdatabase -CircularLoggingEnabled 1

  #lets make a sendconnector
  new-sendconnector -name $sendconnectorname -addressspace * -fqdn $WebmailFQDN -smarthosts mx1.blaaat.com -maxmessagesize 20480

  #next we make a new accepteddomain
  
  new-accepteddomain $companyname -domaintype authoritative -domainname $MailDomain
  set-accepteddomain $companyname -makedefault $true

  #ok time to set the right emailaddresspolicy
  get-emailaddresspolicy | set-emailaddresspolicy -enabledprimarysmtpaddresstemplate "smtp:%m@$MailDomain"

  #now we want to recieve mail from the outside so we need to add anonymoususers to the right recieveconnector
  Get-ReceiveConnector | where {$_.identity -like "*Default*"} | Set-ReceiveConnector -PermissionGroups anonymoususers,exchangeusers,exchangeservers,exchangelegacyservers -MaxMessageSize 20mb

  #owa rules so no need to wait any longer to enable it!
  Enable-OutlookAnywhere -ExternalHostname $externalurl -SSLOffloading $false -DefaultAuthenticationMethod 'Basic'

  Import-ExchangeCertificate -FileData ([Byte[]]$(Get-Content -Path "c:\scripts\$WebmailFQDN.pfx" -Encoding byte -ReadCount 0)) -Password:$certpass
  get-exchangecertificate | where {$_.subject -like "*$WebmailFQDN*"} | enable-exchangecertificate -service imap,pop,smtp,iis -force

  #OK!!! allmost there, lets make sure those spammers dont get trought"

  & 'C:\Program Files\Microsoft\Exchange Server\V14\Scripts\install-AntispamAgents.ps1'
  Write-Host "Watch out!! I`m going to restart the transportservice, are ok with that???"
  Write-Host "just smash the keyboard if you are!!!!"
  $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  Restart-Service msexchangetransport

  #m$ always likes to give you toooooo much, so i need to disable some things.."
  Set-ContentFilterConfig -Enabled $false
  Set-IPAllowListConfig -enabled $false
  Set-IPblockListConfig -enabled $false
  Set-IPBlockListProvidersConfig -enabled $false
  Set-IPAllowListProvidersConfig -enabled $false
  Set-SenderFilterConfig -enabled $false
  Set-SenderIdConfig -enabled $false
  Set-SenderReputationConfig -enabled $false
  Set-RecipientFilterConfig -RecipientValidationEnabled $true

  # finalizing! lets get those systemlogs in the right place!
  Get-MailboxServer | Set-MailboxServer -MessageTrackingLogPath "f:\$companyname ExchangeSystem Logs\messagetrackinglog"
  Get-TransportServer | Set-TransportServer -ConnectivityLogPath "f:\$companyname ExchangeSystem Logs\connectivitylog"
  Get-TransportServer | Set-TransportServer -SendProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpSend"
  Get-TransportServer | Set-TransportServer -ReceiveProtocolLogPath "f:\$companyname ExchangeSystem Logs\ProtocolLog\SmtpRecieve"
}

Function Start-Setup8 {

  Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
 
  $userou = "$companyname.local/ou$companyname/ouUsers/ouInternalUsers"
  $csvfile = "c:\scripts\users.csv"

  Import-CSV $CSVFile | ForEach-Object -Process {New-Mailbox -Name $_.Name -FirstName $_.FirstName -LastName $_.LastName -displayname $_.displayname -alias $_.alias  -UserPrincipalName $_.upn -organizationalunit "$userou" -Password $DefaultUserPassword | set-user -city $_.city -company $_.company -countryorregion $_.countryorregion -fax $_.fax -mobilephone $_.mobilephone -phone $_.phone -postalcode $_.postalcode -streetaddress $_.streetaddress -title $_.title}
}

#
# Main Code
#

If ($PsCmdLet.ParameterSetName -eq "AutoConfig") {

  # Load the settings if we're in autoconfig mode

  $Settings = Import-Csv $ConfigurationFile
  
  $CompanyName = $Settings.CompanyName
  $RestoreModePassword = $Settings.RestoreModePassword
  $AdministratorPassword = $Settings.AdministratorPassword
  $DefaultUserPassword = $Settings.DefaultUserPassword
  $MailDomain = $Settings.MailDomain
  $WebmailFQDN = $Settings.WebmailFQDN
  $ScriptStep = $Settings.ScriptStep

} Else {

  # Set the default configuration file location

  $ConfigurationFile = "settings.csv"

}

# Create / Rewrite the autoconfiguration file and increment the script step

New-Object PsObject -Property @{
  CompanyName = $CompanyName;
  RestoreModePassword = $RestoreModePassword;
  AdministratorPassword = $AdministratorPassword;
  DefaultUserPassword = $DefaultUserPassword;
  Maildomain = $MailDomain;
  WebmailFQDN = $WebmailFQDN;
  ScriptStep = ($ScriptStep + 1);
} | Export-Csv $ConfigurationFile

# Convert the passwords to secure strings

$SecureRestoreModePassword = $RestoreModePassword | ConvertTo-SecureString -AsPlainText -Force
$SecureAdministratorPassword = $AdministratorPassword | ConvertTo-SecureString -AsPlainText -Force

# Validate the certificate path

If (!(Test-Path "C:\Scripts\$WebmailFQDN.pfx")) {
  Write-Error "Certificate file does not exist. Aborting script."
  Break
}

# If this is the first time the script has been called it will run 1
# otherwise it will run each of the remaining steps in sequence

Switch ($ScriptStep) {
  1       {
    New-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript" `
      -Value "PowerShell.exe -NoExit -Command `"C:\Scripts\setup.ps1 -ConfigurationFile $ConfigurationFile`""

    Start-Setup1
  }
  default {

    Start-Setup2
    Start-Setup3
    Start-Setup5
    Start-Setup7
    Start-Setup8


    # Clean up

    Remove-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "SetupScript"
  }
}

Open in new window

what is the modification cause i changed the script for the rest a bit:)
ASKER CERTIFIED SOLUTION
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
well this is strange (i didnt change anything asfar as i know) but now suddenly in  fase 1 i`m getting this error:

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelli
ng of the name, or if a path was included, verify that the path is correct and try again.
At C:\Scripts\huge.ps1:474 char:7
+ } else <<<<  {
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

and that is:

} else {

  # Set the default configuration file location

  $ConfigurationFile = "c:\scripts\settings.csv"

}
Hee Chris

Any idea about my last post?

Sorry, had an assignment due, kind of overrode everything else :)

So, yeah, that's quite puzzling. I can see it doing that if the if statement before it was somehow broken. However, I'm surprised it's not whining about the } before it.

Any chance you can post that bit and a few lines around (maybe 3 either side)?

Chris
thanks! i just had a } wrong!