qazxsw1 发表于 2018-9-3 09:01:43

PowerShell中一个分号引发的问题

  今天在用start-process这个cmdlet去新开一个窗口执行powershell的时候遇到的一个问题
  看一下测试代码:
  以下这个ps代码命名为profile.ps1,并且保存在%UserProfile%\My Documents\WindowsPowerShell这个目录下
  它就相当于是运行powershell时自动加载的脚本,代码如下
  


[*]function print
[*]{
[*]   
[*]Param(
[*]   
[*]    $param1="default1"
[*]
[*]   
[*]    $param2="default2"
[*]    )
[*]
[*]    write-host $param1
[*]    write-host $param2
[*]    Read-Host
[*]}
[*]
  

  然后再由一段执行的代码
  


[*]function Test-Print
[*]{
[*]   
[*]Param(
[*]   
[*]    $param1,
[*]
[*]   
[*]    $param2
[*]    )
[*]    Write-Host $param1
[*]
[*]    $arguments="print $param1 $param2"
[*]    start-process -FilePath "$PSHome\powershell.exe" -ArgumentList $arguments -RedirectStandardError d:\t.log
[*]
[*]}
[*]
[*]Test-Print "test1;ok" "test2"
[*]
  

  最后输出的结果是这样的

  我本意是想输出
  test1;ok
  test2
  我们可以在d:\t.log文件中看到这样的错误信息
  The term 'ok' is not recognized as the name of a cmdlet, function, script file,
  
or operable program. Check the spelling of the name, or if a path was included
  
, verify that the path is correct and try again.
  
At line:1 char:15
  
+ print test1;ok <<<<test2
  
    + CategoryInfo          : ObjectNotFound: (ok:String) [], CommandNotFoundE
  
   xception
  
    + FullyQualifiedErrorId : CommandNotFoundException
  

  

  就是说参数中的分号将它们分开为两个语句了,所以在上下文中并没有定义ok这个东西,所以报这个错。
  我尝试以为可以将分号转义,所以这样运行
  


[*]Test-Print "test1`;ok" "test2"
  

  一样的错误
  我再使用双引号试试?
  


[*]Test-Print "`"test1;ok`"" "test2"
  

  依然是一样的错误
  好吧!咱就只能传数组,在函数中自己解决这个问题了!?
  还有一个问题,就是想上面这样,双引号也是无法传给print这个函数的
  就是说我想打印出的结果想是这样的
  “test1”
  test2
  但实际打印的确是
  test1
  test2


页: [1]
查看完整版本: PowerShell中一个分号引发的问题