PowerShell Script Runs Locally, but Errors on Remote - powershell

I have a PowerShell script I am writing to create new users in our domain, as well as email address. The script works when I run it directly on Exchange. However, if I try to do it from my local PC either with Enter-PSSession or Invoke-Command I get the error:
The term 'Get-ADUser' is not recognized as the name of a cmdlet...
Running that same command from the local machine does work. And running that command on the remote machine works, just not if I run the script remotely.
Here is my script:
$cred = Get-Credential
$first_name = Read-Host -Prompt "What is the new user's first name?"
$last_name = Read-Host -Prompt "What is the new user's last name?"
$copy_from = Read-Host -Prompt "Copy from other user (leave blank if not)?"
$password = Read-Host -Prompt "New user's password?"
$ss_password = ConvertTo-SecureString -String $password -AsPlainText -Force
$new_user_name = $last_name.Substring(0,3) + $first_name.Substring(0,2)
$new_user_name = $new_user_name.ToLower()
Write-Host "Creating user $new_user_name..." -ForegroundColor Green
if ([string]::IsNullOrEmpty($copy_from))
{
Write-Host "Setting up new user (not copying...)" -ForegroundColor Yellow
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -SamAccountName $new_user_name -PassThru | Enable-ADAccount
}
else
{
$copy_from_user = Get-ADUser -Identity $copy_from
Write-Host "Copying user from: " $copy_from_user.Name -ForegroundColor Yellow
$ou = $copy_from_user.DistinguishedName -replace '^cn=.+?(?<!\\),'
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -Path $ou -SamAccountName $new_user_name -PassThru | Enable-ADAccount
$new_user = Get-ADUser -Identity $new_user_name
#Time to copy their group memberships
Get-ADUser -Identity $copy_from -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $new_user_name
}
$pn = $new_user_name + "#INDY"
Set-ADUser -Identity $new_user_name -GivenName $first_name -Surname $last_name -UserPrincipalName $pn
#Now create email
$email_select = Read-Host -Prompt "Select email domain (1. Woodmizer; 2. Lastec; 3. Brightstone)"
if ($email_select -eq 2)
{
$domain = "#lastec.com"
}
elseif ($email_select -eq 3)
{
$domain = "#brightstoneabrasives.com"
}
else
{
$domain = "#woodmizer.com"
}
$email_address1 = $first_name.Substring(0,1) + $last_name + $domain
Write-Host "Creating mailbox $email_address1..." -ForegroundColor Green
Enable-Mailbox -Identity $new_user_name -Database "Mailbox Database 1188513962"
Start-Sleep -s 10
Get-Mailbox -Identity $new_user_name | Set-Mailbox -EmailAddresses #{add="$email_address1"} -EMailAddressPolicyEnabled $false
Get-Mailbox -Identity $new_user_name | Set-Mailbox -PrimarySmtpAddress $email_address1 -EmailAddressPolicyEnabled $false
Write-Host "Finished." -ForegroundColor Green

If you want this script to run on machines that don't have the Active Directory module, you can simply add this to the top of your script to import the cmdlets via session..
$cred = Get-Credential "DOMAIN\adminuser"
$ADsession = New-PSSession -ComputerName DOMAINCONTROLLERNAME -Credential $cred
Import-Module -PSSession $ADsession ActiveDirectory
I also notice you're trying to run Exchange cmdlets..
$exchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://EXCHANGESERVER/PowerShell/" -Authentication Kerberos
Import-PSSession $exchSession

It looks like the ActiveDirectory module is not installed on that machine, you can install the MSFT RSAT tools to get it.

Try the following, It works!! {I tried after giving the Authentication type}
$pass = ConvertTo-SecureString -AsPlainText 'PASSWORD' -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'USERNAME',$pass
$s=New-PSSession SERVERNAME -Credential $MySecureCreds -Authentication Credssp
Invoke-Command -Session $s -scriptblock {
Get-CsUser User
}

Related

New-ADServiceAccount Powershell script is not working

Hi StackOverflow family,
Hope you are well?
I’m facing one issue in the PowerShell script for the last 4 days. I have created/ modified it more than 50 times same script and tested it. every time it is going to catch or get some error. and error is not clear so can't find the cause.
can you help me here?
Thanks
if ($action -like 'create_ad_svc_acc') {
<#
| Set-ADAccountPassword -Identity $svcAccountName -Reset -NewPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
#>
try{
$svcAccountName = "testing_account"
$passwordExp = "no"
$InteractiveLogon = "yes"
#password
$password = "Welcome#1234567890"
#organizational unit
$path = "OU=Service,OU=Accounts,OU=testcompany OU=Administration,DC=domain,DC=internal" #changed the path for company privacy pupose
#Dormant OU
$dormantPath = "OU=Users,OU=Dormant,DC=domain,DC=internal"
#dns host (mandatory)
$dnsHost="test.domain.internal" #changed the host for company privacy pupose
#Set Password expiry
if ($passwordExp -like 'no'){ #environment dependent
$expiryFlag = $True
}
else{
$expiryFlag = $false
}
#create new account
New-ADServiceAccount `
-SamAccountName $svcAccountName `
-name $svcAccountName `
-Enabled $true `
-Path $path `
-DNSHostName $dnsHost `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
sleep 2
if (Get-ADServiceAccount -Identity $svcAccountName){
if ( $InteractiveLogon -like "no"){
Add-ADGroupMember -Identity GBL_DenyLogonLocally -Members $svcAccountName
}
}
Write-Host "Service account has been created"
}
catch{
Write-Warning "There was an error while creating the service account"
}
return
}
As advised in comments, you can display the error by putting the default error output variable in the catch block
When you create an account and want to check it quickly you must query the same domain controller as the one you created it on, else the script can error because it checked another DC but it hadnt yet replicated to that DC
if ($action -like 'create_ad_svc_acc') {
<#
| Set-ADAccountPassword -Identity $svcAccountName -Reset -NewPassword (ConvertTo-SecureString $Password -AsPlainText -Force)
#>
try{
$svcAccountName = "testing_account"
$passwordExp = "no"
$InteractiveLogon = "yes"
#password
$password = "Welcome#1234567890"
#organizational unit
$path = "OU=Service,OU=Accounts,OU=testcompany OU=Administration,DC=domain,DC=internal" #changed the path for company privacy pupose
#Dormant OU
$dormantPath = "OU=Users,OU=Dormant,DC=domain,DC=internal"
#dns host (mandatory)
$dnsHost="test.domain.internal" #changed the host for company privacy pupose
#Set Password expiry
if ($passwordExp -like 'no'){ #environment dependent
$expiryFlag = $True
}
else{
$expiryFlag = $false
}
#create new account
New-ADServiceAccount `
-SamAccountName $svcAccountName `
-name $svcAccountName `
-Enabled $true `
-Path $path `
-DNSHostName $dnsHost `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
sleep 2
### Query the SAME DC we created the account on
if (Get-ADServiceAccount -Identity $svcAccountName -Server $DNSHostname -ErrorAction Stop){
Write-Host "Service account has been created"
if ( $InteractiveLogon -like "no"){
Add-ADGroupMember -Identity GBL_DenyLogonLocally -Members $svcAccountName
}
}
###
}
catch{
Write-Warning "There was an error while creating the service account"
### This var contains the error
$_
###
}
return
}

Rename computer and add join domain powershell script

I am trying to rename a machine and add it to the domain with 1 restart from WORKGROUP (after the machine gets renamed and joined domain). I tried the code below but it's giving me an error:
$bios = (Get-WmiObject Win32_Bios).SerialNumber
$name = $bios
Rename-Computer -NewName "$name"
$domain = "DOMAINNAME"
$username = "USERNAME"
$password = "PASSWORD" | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName $domain -Credential $credential -NewName $name
Read-Host "The computer will restart in 5..."
shutdown /r /t 5
The error I'm receiving is the account already exist. It does join the domain but not the "Renamed" name that I want.
This is how it has to be done.
Rename-Computer -NewName newserver -Force
Add-Computer -DomainName example.ne -Credential $credential -NewName newserver -Options JoinWithNewName
You could better read the full documentation of Add-Computer cmdelt. Get-Help Add-Computer -Online

office 365 bulk add shared mailbox members via powershell

I have already created the shared mailbox in o365.
Now I need to bulk import members to these shared mailboxes.
How to do it in powershell ?
I want to do something like this
$users = import-csv -Path "C:\path\members.csv" -Delimiter ";"
Foreach ($user in $users){
Add-mailboxpermission -identity "name of the shared mail box" -user $user -accessrights FullAccess
}
any thoughts ?
Connecting to Office365 would be a good first step:
$AdminUsername = "admin#your-domain.onmicrosoft.com"
$AdminPassword = "YourPassword"
$AdminSecurePassword = ConvertTo-SecureString -String "$AdminPassword" -AsPlainText -Force
$AdminCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminUsername,$AdminSecurePassword
$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Admincredential -Authentication "Basic" -AllowRedirection
Import-PSSession $ExchangeSession
After you have a session you can play with the functions and add some logic:
$access = "FullAccess"
$mailbox = Get-Mailbox -Identity YourMailbox
$identity = $mailbox.UserPrincipalName
$permissions = Get-MailboxPermission -identity $identity
$users = Import-Csv -Path "C:\path\members.csv" -Delimiter ";"
foreach($user in $users){
try{
$setPermissions = Add-MailboxPermission -Identity $identity -User $user -AccessRights $access
Write-Host "Successfully added permissions for $user" -ForegroundColor Green
}catch{
Write-Host "Failed to add permissions for $user" -ForegroundColor Red
}
}
Remember to add users based on UserPrincipalName

Ask user to choose option from stored list (AD OU Path)

I modified a PowerShell script to create AD and Office 365 accounts automatically, it works fine but helpdesk need to manually type out the OU path.
Is there a way to pre-define OU path & assign number to it so if the helpdesk press 1 it chooses the OU path assigned to number 1 and so on?
Name DistinguishedName
---- -----------------
Departments OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Operational OU=Operational,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Normal OU=Normal,OU=Operational,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTE..
Sales OU=Sales,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Finance OU=Finance,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
IT OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
Application OU=Application,OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,D..
Infrastructure OU=Infrastructure,OU=IT,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTES..
Marketing OU=Marketing,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
NewBusiness OU=NewBusiness,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
ExisitingBusiness OU=ExisitingBusiness,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,D..
Underwritter OU=Underwritter,OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM
#Import needed module.
Import-Module ActiveDirectory
#Prompt for needed information to use as variables below
$fullname = Read-Host "Enter Full Name"
$first = Read-Host "First name"
$last = Read-Host "Last name"
$user = Read-Host "Username"
$title = Read-Host "Title"
Get-ADOrganizationalUnit -Filter * -Properties * -SearchBase "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM" |
Select-Object -Property Name
$department = Read-Host "Enter department from above list"
$manager = Read-Host "Manager userame"
$srcuser = Read-Host "Username to copy"
Get-ADOrganizationalUnit -Filter * -Properties * -SearchBase "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM" |
Select-Object -Property Name, DistinguishedName |
Format-Table -Auto
$OU = Read-Host "Select OU from above list"
#Create a new user with the provided information and some static information
New-ADUser -Name "$fullname" -GivenName "$first" -Surname "$last" -DisplayName "$first $last" -Description "$title" -EmailAddress "$first.$last#bnztest.com" -SamAccountName "$user" -UserPrincipalName "$user#bnztest.com" -Manager "$manager" -Title "$title" -AccountPassword (Read-Host -AsSecureString "Please enter the desired password") -Enabled $true -Path $OU
#Add multiple ProxyAddresses if needed
Set-ADUser "$user" -Add #{ProxyAddresses="smtp:$first.$last#bnztest.com"}
#Copy group membership of the source user above
Get-ADUser -Identity "$srcuser" -Properties memberof |
Select-Object -ExpandProperty memberof |
Add-ADGroupMember -Members "$user" -PassThru |
Select-Object -Property SamAccountName >$null
Write-Host 'CHECK AD REPLICATION BEFORE CONTINUING!'
pause
#Sync user to Office 365 using Dir Sync on a remote server
Import-Module ADSync
Start-ADSyncSyncCycle -PolicyType Initial
Start-Sleep -s 100
#License user in Office 365
$AdminName = "admin#testbnz.onmicrosoft.com"
$Pass = Get-Content "C:\Users\Administrator\Desktop\CreateUser\Cred.txt" |
ConvertTo-SecureString
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminName, $Pass
Import-Module MSOnline
Connect-MsolService -Credential $cred
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Start-Sleep -s 15
Set-MsolUser -UserPrincipalName "$user#bnztest.com" -UsageLocation 'US'
Set-MsolUserLicense -UserPrincipalName "$user#bnztest.com" -AddLicenses "TESTBNZ:O365_BUSINESS_PREMIUM"
Start-Sleep 90
Write-Host 'ENSURE THERE ARE NO ERRORS AND THAT THE MAILBOX HAS BEEN CREATED BEFORE CONTINUING!'
pause
You could add a simple menu like this:
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",
"Exits the loop."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",
"Allows to add another user."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
do
{
$user = New-Object System.Management.Automation.Host.ChoiceDescription "&User", "User"
$it = New-Object System.Management.Automation.Host.ChoiceDescription "&IT", "IT"
$sales = New-Object System.Management.Automation.Host.ChoiceDescription "&Sales", "Sales"
$OUoptions = [System.Management.Automation.Host.ChoiceDescription[]]($user, $it, $sales)
$OU = $host.ui.PromptForChoice("Which OU", "Which OU", $OUoptions, 0)
switch ($OU)
{
0 {Write-Host "The choise is User."}
1 {Write-Host "IT"}
2 {Write-Host "Sales"}
default {Write-Host "The color could not be determined."}
}
$result = $host.ui.PromptForChoice("Continue?", "Do you want to add another user?", $options, 1)
}
while ($result -eq 1)
You can use Out-GridView -OutputMode Single to present the helpdesk with a GUI to select from an object. eg:
$SearchBase = "OU=Departments,OU=Users,OU=Test Enviorment,OU=New Zealand,OU=BNZ,DC=BNZTEST,DC=COM"
$OUList = Get-ADOrganizationalUnit -SearchBase $SearchBase -Filter * -Properties Name,DistinguishedName | Select-Object -Property Name,DistinguishedName
$OU = $OUList | Out-GridView -Title "Select OU and Click OK" -OutputMode Single
Then you can use the OU with your New-ADUser command:
New-ADUser [...] -OU $OU.DistinguishedName

New-ADUser Access denied error with Powershell script

When I run .ps1 I have written to create AD accounts and Mailboxes based on arguments passed to it from a WinForm I am consistently getting the error:
New-ADUser : Access is denied
The script is run when someone clicks a button in a winform and below is the command the button issues:
Powershell.exe "C:\Users\admin\Scripts\usercreationscript.ps1" -department 'Accounting - North America' -GivenName 'test' -Surname 'testlast' -path 'OU=users,DC=domain1,DC=com' -Title 'Sys Admin' -Office 'NJ' -StreetAddress '123 ST' -City 'Moorestown' -PostalCode '08057' -State 'NJ' -Manager 'Jacobb' -MercuryFlag 0 -MirroredUser 'jacobb' -username 'test.testlast'
I have set the execution policy on the remote servers to unrestricted and have also run the Enable-PSRemoting command. The credentials that I supply when prompted are domain administrator credentials. I have also set the trusted hosts to *
When I open the script in Powershell ISE I can connect to remote servers with the Enter-PSSession command I have in the script and can successfully create AD accounts.
I am at a loss as to what is causing the issue.
Full script:
param( [string]$username, [string]$department, [string]$GivenName, [string]$Surname, [string]$path, [string]$Title, [string]$Office, [string]$StreetAddress, [string]$City, [string]$PostalCode, [string]$State, [string]$Manager, [string]$MercuryFlag, [string]$MirroredUser)
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user for Admin rights"
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
#region - Required Functions - ONLY MODIFY AFTER BACKING UP COPY OF SCRIPT
function connect-Domain1AD {
Enter-PSSession -ComputerName DC1.domain1.com -Credential $Credentialdomain1
}
function Connect-Domain1Exchange {
$domain1session = New-PSSession -Authentication Kerberos -ConfigurationName Microsoft.Exchange -ConnectionUri 'http://exchange1.domain1.com/Powershell' -Credential $Credentialdomain1
Import-PSSession $domain1session
}
function Connect-Domain2Exchange {
$session = New-PSSession -Authentication Kerberos -ConnectionUri 'http://exchange1.domain2.com/Powershell' -Credential $Credentialdomain2
Enter-PSSession $Session
}
function Connect-Domain2AD {
Enter-PSSession -ComputerName Dc1.domain2.com -Credential $Credentialdomain2
}
function New-Domain2User{
$userroot ="\\arizona\RemoteAppProfiles\$USERNAME"
New-ADUser `
-name ($givenname + " " + $surname) `
-SamAccountName $Username `
-department $department `
-Title $title `
-office $office `
-StreetAddress $street `
-city $city `
-State $state `
-PostalCode $PostalCode `
-path "OU=users,DC=domain2,DC=com" `
-GivenName $GivenName `
-Surname $Surname `
-DisplayName ($givenname + " " + $surname) `
-userPrincipalName ($username + "#domain2.com") `
-AccountPassword (ConvertTo-SecureString "A temp password." -AsPlainText -force) `
-Enabled $true `
-PasswordNeverExpires $true `
-CannotChangePassword $false `
-ProfilePath \\arizona\RemoteAppProfiles\$Username\ `
-HomeDrive U: `
-HomeDirectory $userroot
Set-ADUser $USERNAME -Add #{extensionattribute14=$username}
}
function New-Domain1User {
New-aduser -name ($givenname + " " + $surname) `
-GivenName $givenname `
-Surname $surname `
-DisplayName ($givenname + " " + $surname) `
-SamAccountName $Username `
-userPrincipalName ($username + "#goevo.com") `
-path $path `
-AccountPassword (ConvertTo-SecureString "A temp password." -AsPlainText -force) `
-Enabled $true `
-PasswordNeverExpires $false `
-CannotChangePassword $false `
-department $department `
-Title $title `
-office $office `
-StreetAddress $street `
-city $city `
-State $state `
-PostalCode $zipcode `
-Manager $Manager
}
function New-Domain1Mailbox {
Enable-mailbox -identity $username
Set-Mailbox -identity $username `
-customAttribute1 "Domain1" `
-customAttribute2 "user" `
-customAttribute3 "Internal" `
-customAttribute5 $office `
-customattribute6 $department `
-customattribute7 $ca7 `
-customattribute8 $ca8
}
#endregion - Required Functions
Write-Host $MercuryFlag
If($MercuryFlag -eq '1' ){
Set-variable -name Credentialdomain2 -value $Host.ui.PromptForCredential("Need Domain2 credentials", "Please enter your Domain2 user name and password:", "", "Domain2.com") -scope global
Connect-Domain2AD
import-module activedirectory
New-Domain2User
Exit-PSSession
get-pssession | remove-pssession
Set-variable -name Credentialdomain1 -value $Host.ui.PromptForCredential("Need Domain1 credentials", "Please enter your Domain1 user name and password:", "", "Domain1.com") -scope global
connect-Domain1AD
New-Domain1User
Exit-PSSession
get-pssession | remove-pssession
Connect-Domain1Exchange
New-Domain1Mailbox
Exit-PSSession
get-pssession | remove-pssession
}
else {
Set-variable -name Credentialdomain1 -value $Host.ui.PromptForCredential("Need Domain1 credentials", "Please enter your Domain1 user name and password:", "", "Domain1.com") -scope global
connect-Domain1AD
New-Domain1User
Exit-PSSession
get-pssession | remove-pssession
Connect-Domain1Exchange
New-Domain1Mailbox
Exit-PSSession
get-pssession | remove-pssession
}
I was able to fix it by changing
:
function connect-Domain1AD {
Enter-PSSession -ComputerName DC1.domain1.com -Credential $Credentialdomain1
}
to
function connect-Domain1AD {
$domain1ad = new-pssession -ComputerName DC1.domain1.com -Credential $Credentialdomain1
Invoke-Command –Session $domain1ad –ScriptBlock {Import-Module ActiveDir*}
Import-PSSession –Session $domain1ad –Module ActiveDir* -AllowClobber
}