Home > other >  how to run multiple powershell command inside .bat
how to run multiple powershell command inside .bat

Time:03-02

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related