【问题标题】:Problems when calling PowerShell with instructions as parameters使用指令作为参数调用 PowerShell 时出现问题
【发布时间】:2018-10-21 18:08:30
【问题描述】:

我正在编写一个程序,该程序涉及运行 PowerShell 并将指令作为第一个参数传递。我传递了多个指令并将它们与; 链接在一起。在调试和测试之后,我认为我找到了问题的本质,老实说,我无法判断这是 PowerShell 故障还是我只是非常愚蠢。 “故障”基本上归结为以下几点:

如果你打开 PowerShell 并运行:

$string = "test"; Add-Content "A:\file.txt" $string 

您获得了一个 file.txt,它包含“test”,正如预期的那样。 现在,如果您改为从终端调用 PowerShell,并将此指令作为参数传递,您将获得 file.txt,但其中没有内容,尽管命令相同。我的猜测是,当指令作为参数传递时,$string 变量在; 之后被丢弃,但我知道什么。有没有办法解决,还是我遗漏了一些明显的东西?

【问题讨论】:

    标签: windows powershell terminal arguments parameter-passing


    【解决方案1】:
    powershell $x="test"; add-content c:\path\test.txt $x
    

    被视为类似

    powershell 
        $x="test";        # run this script code
    
            add-content   # with this as parameter 1
            c:\sc\q.txt   # with this as parameter 2
            $x            # with this as parameter 3
    

    你想引用它,所以所有脚本都是 powershell.exe 的一个参数,更像这样:

    powershell "$x='test'; add-content c:\path\test.txt $x"
    

    【讨论】:

    • 非常感谢,就是这样!我确信我试过了,但它没有用,但我一定是犯了一个错误
    猜你喜欢
    • 2022-12-10
    • 2019-10-20
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多