• PowerShell中一个分号引发的问题


    今天在用start-process这个cmdlet去新开一个窗口执行powershell的时候遇到的一个问题

    看一下测试代码:

    以下这个ps代码命名为profile.ps1,并且保存在%UserProfile%\My Documents\WindowsPowerShell这个目录下

    它就相当于是运行powershell时自动加载的脚本,代码如下

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

    然后再有一段执行的代码

    function Test-Print 
    { 
        [CmdletBinding()] 
    Param( 
        [ValidateNotNullOrEmpty()] 
        $param1, 
        
        [ValidateNotNullOrEmpty()] 
        $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" 

    最后输出的结果是这样的

    Capture

    我本意是想输出

    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

  • 相关阅读:
    ACM 人见人爱A^B
    ACM Max Factor
    ACM Primes
    ACM Least Common Multiple
    ACM 最小公倍数
    ACM Bone Collector
    ACM 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活
    ACM Piggy Bank
    ACM 饭卡
    ACM Where is the Marble?
  • 原文地址:https://www.cnblogs.com/heqichang/p/2567829.html
Copyright © 2020-2023  润新知