从powershell脚本运行批处理文件(带空格)

时间:2014-01-31 18:03:38

标签: windows batch-file powershell

我需要从powershell脚本调用批处理文件。批处理文件名将使用用户的PS文件参数决定。我有这个代码但没有按预期工作。有人会把我的错误误认为我吗?一切似乎都很好,但我遇到实际批处理文件调用问题(最后4个语句之一)

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`""

2 个答案:

答案 0 :(得分:1)

试试这个

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

注意:如果从用户输入的文本执行代码,我通常不建议使用Invoke-Expression。例如,考虑如果您使用Read-Host询问用户的用户名并在; Remove-Item C:\ -Recurse -Force -ErrorAction 0;中键入内容会发生什么。是的,那对你来说可能是糟糕的一天。

在V3 / V4上你也可以使用--%,但它需要将你的信息存储在你可能不想用密码做的env vars中:

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

请参阅此post for more details on --%

答案 1 :(得分:0)

您是否有理由想用cmd.exe / k启动它?

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