繁体   English   中英

从批处理将参数传递给Powershell脚本放置空格

[英]Passing argument to powershell script from batch puts spaces

我正在使用批处理文件runpowershellscript.bat调用powershell脚本sample.ps1。 当我将参数传递给批处理文件时,该批处理会将该参数发送给powershell脚本。 当我在sample.ps1中打印参数时,参数周围有一个空格。 为什么要增加该空间?

runpowershellscript.bat

@echo off

setlocal
SET SCRIPT=%1
SET PATH=%PATH%;C:\Windows\System32\WindowsPowershell\v1.0\

if "%2"=="" (
REM no arguments
powershell -executionpolicy bypass -File %1
goto :END
)

if not "%3"=="" (
REM 2 arguments
powershell -executionpolicy bypass -File %1 %2 %3
goto :END
) 

if not "%2"=="" (
REM 1 argument
powershell -executionpolicy bypass -File %1 %2
goto :END
) 

:END
endlocal

sample.ps1

Write-Host "number of arguments=" $args.Count

for($i = 0; $i -lt $args.Count; $i++) {
    Write-Host "[",$args[$i],"]"
}
Write-Host ""

if ($args[0]) {
Write-Host "Hello,",$args[0]
}
else {
Write-Host "Hello,World"
}

Powershell版本

PS C:\eclipse\batch> Get-Host


Name             : ConsoleHost
Version          : 2.0
InstanceId       : 7b72da6c-5e6c-4c68-9280-39ae8320f57e
UI               : System.Management.Automation.Internal.Host.InternalHostUserI
                   nterface
CurrentCulture   : en-GB
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

当我运行批处理时,下面的命令行内容

C:\batch>.\runpowershellscript.bat sample.ps1 firstarg
number of arguments= 1
[ firstarg ]

Hello, firstarg

请注意,ps1脚本中的Hello和$ args [0]之间没有空格。 我没想到Hello和firstarg之间会有空格。

谢谢。

您使用了错误的串联运算符。 通过使用逗号,您将数组而不是字符串传递给Write-Host ,因此它在元素之间添加了空格。

请尝试:

if ($args[0]) {
  Write-Host "Hello,$($args[0])"
}

那应该解决。

暂无
暂无

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

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