3

I made a batch file for joining computers to domain.

Powershell -command " Add-Computer -DomainName blabla.com -Credential blabla\bla "

works but I also want to add -Description with input.

Powershell -command "
$date = Get-Date
$cred= read-host -prompt 'IT username' 
Add-Computer -DomainName blabla.com  -Description "joined domain by $cred date $date" -Credential blabla\$cred "

did not work.

Powershell -command " $date = Get-Date "
Powershell -command " $cred= read-host -prompt 'IT username' "
Powershell -command " Add-Computer -DomainName blabla.com  -Description "joined domain by $cred date $date" -Credential blabla\$cred "

didnt work either.

Please I need help

Compo
  • 36,585
  • 5
  • 27
  • 39
Berke the Vulpes
  • 45
  • 1
  • 1
  • 6
  • 4
    Welcome to SO, Berke the Vulpes. Each individual invocation of `powershell.exe` does not know what the other did. The commands can be in one PowerShell invocation by using a SEMICOLON at the end of each line. – lit Mar 01 '22 at 13:56
  • 4
    You need just one execution of PowerShell, and multiple commands passed to it. Each of those commands should be separated with semicolons, `;`, and should all be enclosed within one doublequoted `-Command` argument. – Compo Mar 01 '22 at 13:57
  • 1
    Does this answer your question? [Using multi-line PowerShell commands from cmd.exe](https://stackoverflow.com/questions/45224759/using-multi-line-powershell-commands-from-cmd-exe) – stackprotector Mar 01 '22 at 14:16

2 Answers2

4

This needs to be done in a single invocation of powershell.exe. Terminate each PowerShell statement with a SEMICOLON and use the cmd line continuation character, CARET ^.

powershell -command ^
$date = Get-Date; ^
$cred= read-host -prompt 'IT username'; ^
Add-Computer -DomainName blabla.com  -Description "joined domain by $cred date $date" -Credential blabla\$cred;

The reason this needs to be one invocation is that separate invocations of PowerShell do not know what each other has done.

This is not tested. There may be some cmd syntax issues, typically about quoting. It would be easier to have the .bat file script call a PowerShell script.

powershell -NoLogo -NoProfile -File "%~dpDo-JoinDomain.ps1"

Note that Do is not an approved PowerShell verb. Use the command Get-Verb to find one you think is suitable.

lit
  • 14,456
  • 10
  • 65
  • 119
1
@echo off
Powershell -command " $date = Get-Date; $cred= read-host -prompt 'IT username'; add-Computer -DomainName tpicomp.com -Description "joined domain by $cred date $date" -Credential tpicomp\$cred "

thanks for @lit and @Compo here is the final result.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Berke the Vulpes
  • 45
  • 1
  • 1
  • 6