简体   繁体   English

从Powershell脚本运行批处理文件(带空白)

[英]Running a batch file (with blanks) from powershell script

I need to call a batch file from powershell script. 我需要从Powershell脚本调用批处理文件。 The batch file name will be decided using the parameters to PS file from user. 批处理文件名将由用户使用PS文件的参数来确定。 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) 一切似乎都很好,但是我在调​​用实际的批处理文件时遇到了问题(最后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`""

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. 注意:如果从用户输入的文本执行代码,我通常不建议使用Invoke-Expression。 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; 例如,考虑一下如果您使用Read-Host询问用户的用户名并输入; Remove-Item C:\\ -Recurse -Force -ErrorAction 0;会发生什么情况; Remove-Item C:\\ -Recurse -Force -ErrorAction 0; ; 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: 在V3 / V4上,您也可以使用--%但是它需要将您的信息存储在env vars中,而您可能不想使用密码:

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

See this post for more details on --% . 有关-%的更多详细信息,请参见这篇文章

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM