Workflow Rename-DC
{
dcpromo /unattend:C:\Payload\AnswerFile.xml
Checkpoint-Workflow
New-ADOrganizationalUnit -Name "Admin" -Path "DC=ProjectX,DC=com"
Add-KdsRootKey EffectiveImmediately
New-ADServiceAccount -Name "Test Account" -DNSHostName "DC1.ProjectX.com" -Enabled $true
New-ADUser -Name "HelpDesk" -GivenName "Helpdesk" -Surname "" -SamAccountName helpdesk -UserprincipalName helpdesk#ProjectX.com -Path "OU=Admin,DC=ProjectX,DC=com"
Unregister-ScheduledJob -Name RenameDCResume
}
$Admin = "Administartor"
$Password = ConvertTo-SecureString -String "Passw0rd" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential($Admin, $Password)
$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name RenameDCResume `
-Credential $Cred `
-Trigger $AtStartup `
-ScriptBlock {Import-Module PSWorkflow; `
Get-Job -Name RenameDomainController -State Suspended `
| Resume-Job}
Rename-DC -JobName RenameDomainController
Looking for some help with my workflow in PowerShell. the plan is to get the script to continue after the computer reboots for installation of the DC at line 3. However, the script doesn't seem to be continuing as planned at start up. Any ideas what I can do to correct this? Also, is the checkpoint after the dcpromo correct? Will it still take a checkpoint or will it ignore this as the reboot has already begun? would a PSPersist work better? Thanks in anticipation.
Related
For starters i made the below script for PS 5.1 (i know that PS 6.0 has the Remove-Service option but not 5.1).
I have all the required .exe, dll's and config's along with this script that is packaged as an artifact and will be deployed on the Headnode directory of the target.
Not sure if the below script will uninstall and install the service. But i can see that it is deleting and starting the new service when i run it.**
```
$acl = Get-Acl "C:\Program Files\Matt\Wservice"
$aclRuleArgs = "XYZ", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
if (Get-Service "Wservice" -ErrorAction 'SilentlyContinue')
{
Stop-Service -Name Wservice -ErrorAction SilentlyContinue -Force
(Get-WmiObject -Class Win32_Service -filter "Name='Wservice'").delete()
Write-Host "Please wait until removing the : Wservice "
Start-Sleep -s 30
}
$Username = 'xyz'
$Password = '123'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
New-Service -Name Wservice -BinaryPathName "C:\Program Files\Matt\Wservice\Wservice.exe" -Credential $MySecureCreds -DisplayName "WserviceService" -StartupType Automatic
Start-Service -Name "Wservice"
```
Powershell core 6.0/7.0 dosent seem to have get-wmiobject, WMI is depreceated, then we have to use CIM using Get-CIMInstance.
Rest all seem OK. Coreected code:
$acl = Get-Acl "C:\Program Files\Matt\Wservice"
$aclRuleArgs = "XYZ", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
if (Get-Service "Wservice" -ErrorAction 'SilentlyContinue')
{
Stop-Service -Name Wservice -ErrorAction SilentlyContinue -Force
(Get-CIMInstance -Class Win32_Service -filter "Name='Wservice'").delete()
Write-Host "Please wait until removing the : Wservice "
Start-Sleep -s 30
}
$Username = 'xyz'
$Password = '123'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
New-Service -Name Wservice -BinaryPathName "C:\Program Files\Matt\Wservice\Wservice.exe" -Credential $MySecureCreds -DisplayName "WserviceService" -StartupType Automatic
Start-Service -Name "Wservice"
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
}
I am using this powershell script below to license bulk users in office365 by .csv file. The script will only work if the .csv file header is:
UserPrincipalName
example#jackson.k12.ms.us
But our .csv is formatted: "Alias","UPN"
"myrobinson","myrobinson#jackson.k12.ms.us"
I want to know how to recode this script so it works with our .csv file?
$path= Import-Csv -Path "\\11.10.38.142\Users\myrobinson\NewUsers.csv"
foreach ($item in $path){
$MSOLUserName= $item.UserPrincipalName
$password = ConvertTo-SecureString "support#Jpsd" -AsPlainText –Force
$credential = New-Object System.Management.Automation.PsCredential("admin#jpsd.onmicrosoft.com",$password)
$cred = Get-Credential -cred $credential
Import-Module MSOnline
Connect-Msolservice -cred $cred
$AccountSkuId = "jpsd:STANDARDWOFFPACK_FACULTY"
$UsageLocation = "US"
$LicenseOptions = New-MsolLicenseOptions -AccountSkuId $AccountSkuId
Set-MsolUser -UserPrincipalName $MSOLUserName -UsageLocation $UsageLocation
Set-MsolUserLicense -UserPrincipalName $MSOLUserName -AddLicenses
$AccountSkuId -LicenseOptions $LicenseOptions
}
Just replace $item.UserPrincipalName with $item.UPN.
I have a simple snippet I can run no problems within the powershell console. When I compile it to an EXE, or even a ps1 and run it, it doesn't find the reg value, no idea why.
Here is the code:
$User = "Training\Administrator"
$PWord = ConvertTo-SecureString -String "P#ssWord" -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$creds = $Credentials
enter-pssession –computername Win7Client –credential $creds
Start-Sleep -s 2
Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore
Return
I would change the last lines to:
$Pssn = new-psssession –computername Win7Client –credential $creds
invoke-command -Session $Pssn -scriptblock {Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore }
Return
Hope this helps,
Luc
Weird problem I saw today and I don't understand.
Is there a difference beetween running a script manually in the ISE or Pshell, and as a job?
If I run it manually the code doesn't throw an error - runs smoothly:
Get-ChildItem "\\SERVER\S$\ROOT\DIR" -Recurse | Where {$_.creationtime -lt (Get-Date).AddDays(-35)} | Remove-Item -Force -Include *.conf
But if I run it via Job and let the it export the $error to a txtfile this happens:
Are the rights of my running machine different to the rights of the scheduled job?
Get-ChildItem : Zugriff verweigert
In Zeile:81 Zeichen:1
+ Get-ChildItem "\\SERVER\S$\ROOT\DIR" -Recurse | Where
{$_.creati ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ChildItem], UnauthorizedA
ccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
erShell.Commands.GetChildItemCommand
Zugriff verweigert = Access denied
Oh, totally forgot to tell about my windows rights.
Normally the Server I am connecting to is blocked for everybody - except for login with credentials ofc. But somehow my manual powershell script is able to delete and create files?
In "job-mode" it loses it's abilities.
Edit:
Same for the Test-Path commandlet. Manually it shows me true or false. Via job it throws an error.
EDIT - SAME PROBLEM COMPLETELY DIFFERENT Commandlets:
$username = "Administrator"
$password = cat C:\securestring.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
New-PSDrive -Name Z -PSProvider FileSystem -Root \\Server\ROOT -Credential $cred -Persist
test-path 'Z:'
Remove-PSDrive -Name Z -PSProvider FileSystem
This works!
This does not:
$jobname = "Test5"
$JobTrigger = New-JobTrigger -Daily -At "00:18 PM"
$MyOptions = New-ScheduledJobOption -ContinueIfGoingOnBattery -HideInTaskScheduler -RunElevated
Register-ScheduledJob -name "$jobname" -scriptblock {
$username = "Administrator"
$password = cat C:\securestring.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
New-PSDrive -Name Z -PSProvider FileSystem -Root \\Server\ROOT -Credential $cred -Persist
test-path 'Z:'
Remove-PSDrive -Name Z -PSProvider FileSystem
} -trigger $JobTrigger –ScheduledJobOption $MyOptions
You probably have the job running under the SYSTEM account. Use the -Credential parameter to provide your account credentials (whatever account you're logged in with when you successfully run the command interactively).
BTW, Register-ScheduledJob uses the Task Scheduler. You can check the properties of the job in Task Scheduler to see what account it's configured to run as.
Well, it is not exactly an answere to my original question, but I was able to work around my problem by using the invoke-command and test-path from there and giving argument via the -arg.
Invoke-Command -ComputerName $FTPADRESS -ArgumentList $DIRECTORY -ScriptBlock {param ($DIR)
$check = Test-Path -Path "\\SERVER\ROOT\$DIR"
if ($check -ne $true) {New-Item -ItemType directory -Path "\\SERVER\ROOT\$DIR"}
}
Same works with the get-childitem.