Here is my code
# Create New Domain Controller
Import-Module ADDSDeployment
Install-ADDSDomainController -InstallDns -Credential (Get-Credential BPLTest.lab\Administrator) -DomainName "BPLtest.lab"
-NoGlobalCatalog:$false
-InstallDns:$True
-CreateDnsDelegation:$false
-CriticalReplicationOnly:$false
-DatabasePath "C:\NTDS"
-LogPath "C:\NTDS"
-SysvolPath "C:\SYSVOL"
-NoRebootOnCompletion:$false
-SiteName "Default-First-Site-Name"
-Force:$true
Now this code should install a domain controller into the my BPLTest.lab domain in my lab. I have run the ad prerequistes and also added RSAT tools for AD in another prior script. They work perfectly. However this script will install domain controller but I cant get it adjust things like the SysvolPath, DatabasePath and logpath. It keeps telling me it doesnt recognise these cmdlets.
ANy ideas what I am doing wrong
PowerShell will assume the Install-ADDSDomainController line is complete and won't look on the next lines for more parameters.
You need to tell it there is more to the command by ending a line with a backtick:
#Create New Domain Controller
Import-Module ADDSDeployment
Install-ADDSDomainController -InstallDns -Credential (Get-Credential BPLTest.lab\Administrator) -DomainName "BPLtest.lab" `
-NoGlobalCatalog:$false `
-InstallDns:$True `
-CreateDnsDelegation:$false `
-CriticalReplicationOnly:$false `
-DatabasePath "C:\NTDS" `
-LogPath "C:\NTDS" `
-SysvolPath "C:\SYSVOL" `
-NoRebootOnCompletion:$false `
-SiteName "Default-First-Site-Name" `
-Force:$true
Or by putting the variables into a dictionary of parameters first, and then 'splatting' them into the cmdlet as described here: https://stackoverflow.com/a/24313253/478656
Related
How can I start a service on an Azure VM remotely? It seems impossible to do without Powershell being "Run as Administrator". Is there a way to launch as admin?
(I would pass in Get-Credential parameter, but unfortunately the 5.1 version Set-Service command does not accept that as a parameter like it does in Powershell version 7.x, and i am limited to 5.1 for now.)
My credentials do have admin level rights on the VM, but i can't seem to figure out a way to pass that via a command.
I am triggering the call like this, where $action is either 'stop' or 'start':
$runCommand = Invoke-AzVMRunCommand `
-ResourceGroupName $rg `
-VMName $vm `
-CommandId 'RunPowerShellScript' `
-ScriptPath $scriptPath `
-Parameter #{action = $action}
The linked script would then execute something like this:
$serviceNames = #("service1, service2")
foreach($serviceName in $serviceNames){
$service = Get-Service -Name $serviceName
if($service){
if($action -ieq "start"){
Set-Service -InputObject $service -Status "Running"
}
}
else{
Write-Output "Service $serviceName not found!"
}
}
When i run from my laptop - it hangs.
When i run from Azure portal via "Run Command" - it hangs.
When i run from the VM itself - it says:
"Service '' cannot be configured due to the following error:
Access is denied
When i run from the VM itself but start Powershell as admin - It works!
Make sure you have to connect with local administrator password which you already configured with your VM.
If you are not able to connect the VM you need to reset your local administrator password/ Remote Desktop Service Configuration as per MS-DOC. We can reset either Azure Portal / VM Access extension and PowerShell.
If you want to connect the Azure VM from your local, you have to signed in with respective Azure subscription.
Use Set-AzVMAccessExtension to reset the local administrator account password.
VM has a single Access Agent. Use the same VM Access Agent which you used earlier.
Workaround
Way 1
Add the user to your VM
$Uname = "<UserName>"
$password = "<Password>"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-LocalUser $Uname -Password $securePassword -FullName $Uname -Description "test admin account"
Add-LocalGroupMember -Group "Administrators" -Member $Uname
Way 2
Reset the local Administrator password
$vm = Get-AzVM -ResourceGroupName "<ResourceGroup Name>" -Name "<Resource name>"
$Uname = "<UserName>"
$password = "<Password>"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ($Uname, $securePassword)
Set-AzVMAccessExtension -Credential $credentials -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -Location $vm.Location -Name VMAccessAgent -TypeHandlerVersion "2.0"
Access the Script file using specific login
Connect-AzAccount
$vm = Get-AzVM -Name "<your vm name>" -ResourceGroupName "<your vm resource group>"
$runCommand = Invoke-AzVMRunCommand `
-ResourceGroupName $rg `
-VMName $vm `
-CommandId 'RunPowerShellScript' `
-ScriptPath $scriptPath `
-Parameter #{action = $action}
I'm tring to run Powercli script from VM that have all the modules nedded.
The script should insert other VM to domain.
$ScriptText ="Add-Computer -DomainName foofoo.com -DomainCredential " + $DomainC +" -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'"
echo $Script
Invoke-VMScript -vm $VMName -GuestCredential $AdminC -ScriptText $ScriptText
all the variables inserted correctly.
runing
Add-Computer -DomainName foofoo.com -DomainCredential $DomainC -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
from the other vm poweshell console is running well and the output message WARNING: The changes will take effect after you restart the computer ..
$Script return:
Add-Computer -DomainName foofoo.com -DomainCredential System.Net.NetworkCredential -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
but after that this script stuck and I have no error or other output.
Any idea what is the reason for that ?
The Add-Computer CMDlet takes a credential object for the domain credential parameter. By trying to convert that to a string in your $scripttext variable - you're losing the credential type in the conversion. You need to make a credential object inside your script text rather than passing in a variable containing the credential object. This adds some complexity because you generally want to pull a password from a secure vault. The below examples shows how to include the password as a plain text - but this isn't really advised for obvious reasons.
$scripttext = #'
$user = "UserName"
$password = ConvertTo-SecureString "bar" -AsPlainText -Force
$DomainC = New-Object PSCredential $user, $password
Add-Computer -DomainName foofoo.com -DomainCredential $DomainC -OUPath 'OU=CACI,OU=Computers,OU=bla,OU=Regions,DC=bla,DC=com'
'#
Invoke-VMScript -vm $VMName -GuestCredential $AdminC -ScriptText $ScriptText
Hello,
I am trying to automate the installation and promotion of domain controllers, which are being added to an existing root forest with no child domains. I'm using the following code to perform this action during a ConfigMgr Task Sequence (so the script itself is being run as System):
function Install-DomainController
{
param(
[string]$CUST_DSRMPassword,
[System.Management.Automation.PSCredential]$CUST_ADDSCredentials
)
Write-LogEntry -Type Information -Message "Promoting the Server to a Domain Controller..."
try
{
Install-ADDSDomainController `
-NoGlobalCatalog:$false `
-CreateDNSDelegation:$false `
-CriticalReplicationOnly:$false `
-Credential $CUST_ADDSCredentials `
-Adprepcredential $CUST_ADDSCredentials `
-DatabasePath "$NTDSPath" `
-DomainName "$DomainName" `
-InstallDNS:$true `
-LogPath "$NTDSPath" `
-ReplicationSourceDC "$CUST_DomainControllerToUse" `
-SysvolPath "$SysvolPath" `
-Force:$true `
-NoRebootOnCompletion:$true `
-SafeModeAdministratorPassword (ConvertTo-SecureString -AsPlainText $CUST_DSRMPassword -Force)
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-LogEntry -Type Error -Message "The Item '$FailedItem' caused the following error: '$ErrorMessage'!"
}
}
The credentials are being passed as a parameter formatted as [System.Management.Automation.PSCredential]. I can verify the credentials are correct by opening a cmd window, running powershell and using the following code during runtime:
$CUST_ADDSCredentials.Password
$CUST_ADDSCredentials.GetNetworkCredential()
$CUST_ADDSCredentials.GetNetworkCredential().Password
And I know the user I'm passing on to the cmdlet is infact a member of the domain admins, enterprise admins and schema admins. Yet I still recieve the following error message:
User is not DA or EA. VerifyUserCredentialPermissions error message:
You have not supplied user credentials that belong to the Domain
Admins group or the Enterprise Admins group. The installation may fail
with an access denied error. Do you want to continue?
I'm puzzled as to what I'm doing wrong here. Would I perhaps be required to run the cmdlet in a different context by opening a seperate PSSession and using Invoke-Command -Session -ScriptBlock{}? Or is there perhaps something obvious I'm missing?
Thankful for any help :-)
Best Regards,
Fred
I'm using a Powershell script to run another sql script. My issue is that this script is running at some point but then it stops and restart from the beginning.
Do you have any idea why is it doing this?
Here's the Ps1 script I'm talking about:
Invoke-Sqlcmd -InputFile "$script.sql" `
-Database $database `
-Server $server `
-UserName $username `
-Password $password `
-QueryTimeout 65534 `
-Verbose | Out-Null) 4> "$script.log"
is it related somehow to the Timeout I've set?
Thanks a lot!
I am trying to setup an Endpoint-Server in my company and am struggling to connect to it. For testing I put a RcLogUtil Module in the Global Module Path
C:\windows\system32\WindowsPowershell\v1.0\Modules\RcLogUtil\
that exports the functions
'Out-LogToEventLog','New-LogMessage'
The Plan is to let a specific set of users access only those Logging-Functions.
I create a SessionConfiguration:
New-PSSessionConfigurationFile -Path C:\Scripts\LoggerEp.pssc `
-SessionType RestrictedRemoteServer `
-LanguageMode FullLanguage `
-ExecutionPolicy Unrestricted `
-ModulesToImport 'RcLogUtil' `
-VisibleFunctions 'Out-LogToEventLog' `
-VisibleCmdlets 'Split-Path'
Register it:
Register-PSSessionConfiguration -Path C:\Scripts\LoggerEp.pssc `
-Name loggerep `
-ShowSecurityDescriptorUI
And enter it on my local machine:
[W0216]> Enter-PSSession -ComputerName mka-ps-endpoint -ConfigurationName loggerep
Enter-PSSession : One or more errors occurred processing the module
'RcLogUtil' specified in the InitialSessionState object used to create
this runspace. See the ErrorRecords property for a complete list of
errors. The first error was: The term 'Split-Path' is not recognized
as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that
the path is correct and try again. At line:1 char:1
+ Enter-PSSession -ComputerName mka-ps-endpoint -ConfigurationName loggerep
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Enter-PSSession], RunspaceOpenModuleLoadException
+ FullyQualifiedErrorId : ErrorLoadingModulesOnRunspaceOpen
The huge question now is.. why is the Session unable to find Split-Path? Or how do I tell the Endpoint to load that particular cmdlet?
I successfully tried the same with SessionType=’Default’ and it worked but with all the powershell clutter around it.
I would really apreciate any help I can get as I am stuck with this for quite some time now..
Thanks!
There is the option to disable each cmdlet in advance by using -SessionType Default with the -ScriptsToProcess 'C:\Scripts\LoggerEpStartup.ps1' Parameter when creating a SessionConfiguration.
New-PSSessionConfigurationFile -Path C:\Scripts\LoggerEp.pssc `
-SessionType Default `
-LanguageMode FullLanguage `
-ExecutionPolicy Unrestricted `
-ModulesToImport 'RcLogUtil' `
-VisibleFunctions 'Out-LogToEventLog' `
-ScriptsToProcess 'C:\Scripts\LoggerEpStartup.ps1'
C:\Scripts\LoggerEpStartup.ps1:
# Commands needed by PSSession (Also the commands used when
# creating a RestrictedRemoteServer )
$CmdsToExclude = #(
'Get-Command' , 'Out-Default' ,
'Exit-PSSession', 'Measure-Object',
'Select-Object' , 'Get-FormatData'
)
# Hide any other commandlets except the ones needed
# to create a remote session
Get-Command | Where Visibility -eq 'Public' | ForEach-Object {
if ( $_.Name -notin $CmdsToExclude ) {
$_.Visibility = 'Private'
}
}
But I want to avoid that aproach as it seems to be more of a clumsy workaround than a proper solution.