1

I need to call a batch file from powershell script. The batch file name will be decided using the parameters to PS file from user. I have this code but not working as expected. Could someone poing me my mistake? Everything seems fine but I am getting issues with the actual batch file calling (one of the last 4 statements)

param(
  [string]$parts
)
$sharedDrive = "\\server\share"
$cred = get-credential "DOMAIN\"
$username = $cred.UserName
$password = $cred.GetNetworkCredential().Password
$net = New-Object -com WScript.Network
$net.mapnetworkdrive("", $sharedDrive, "true", $username, $password)

$BatchFilePath = $sharedDrive + "\Public\Upgrade\Application Folder"
IF ($parts -eq "P1") {
    $selectedBatchFile = "`"" + $BatchFilePath + "\P1 Upgrade File.bat" + "`""
} ELSEIF ($parts -eq "P2") {
    $selectedBatchFile = "`"" + $BatchFilePath + "\P1P2 Upgrade File.bat" + "`""
} ELSE {
     Write-Host "Invalid Part specified. Choose one from: P1, P2"
}

$command1 =  "/k $selectedBatchFile   $username   $password"

## I tried all the below but NONE worked

#& cmd "`"$command1`""
#& cmd "$command1"

#Start-Process "cmd.exe" -ArgumentList "$command1"
#Start-Process "cmd.exe" -ArgumentList "`"$command1`""
1
  • I've used Invoke-CmdScript to call batch files, with params, from powershell. Commented Jan 31, 2014 at 18:56

2 Answers 2

1

Try this

Invoke-Expression "cmd /k `"$selectedBatchFile`" $username $password"

NOTE: I do not normally suggest using Invoke-Expression if it executes code from text that a user has input. For instance, think about what happens if you use Read-Host to ask the user for their username and they type in ; Remove-Item C:\ -Recurse -Force -ErrorAction 0;. Yeah, that might be a bad day for you.

On V3/V4 you could also use --% but it requires storing your info in env vars which you might not want to do with a password:

$env:file = $selectedBatchFile
$env:un = $username
$env:pw = $password
cmd.exe /c --% "%file%" %un% %pw%

See this post for more details on --%.

Sign up to request clarification or add additional context in comments.

2 Comments

I couldnt use the env solution. First one did not work.
If you can, I highly recommend updating to at least V3 (V4 is currently the latest). Calling exes with parameters has been a major source of frustration and was at least partially addressed by the --% operator in V3.
0

Is there a reason you want to start it with cmd.exe /k?

start-process -filepath $selectedbatchfile -argumentlist $username,$password

1 Comment

It did work Thank you. start-process -Wait -NoNewWindow -filepath cmd -argumentlist "/c", $selectedbatchfile, $username, $password

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.