[英]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.