Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run multiple powershell command inside .bat

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

like image 566
Berke the Vulpes Avatar asked Nov 15 '25 09:11

Berke the Vulpes


2 Answers

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.

like image 177
lit Avatar answered Nov 17 '25 08:11

lit


@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.

like image 31
Berke the Vulpes Avatar answered Nov 17 '25 08:11

Berke the Vulpes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!