powershell - 如何从命令行运行 Powershell 脚本并将目录作为参数传递

标签 powershell powershell-2.0

PowerShell -Command .\Foo.ps1
  • Foo.ps1:

    Function Foo($directory)
    {
        echo $directory
    }
    
    if ($args.Length -eq 0)
    {
        echo "Usage: Foo <directory>"
    }
    else
    {
        Foo($args[0])
    }
    

    尽管 Foo.ps1 位于我调用 Powershell 的目录中,但这会导致:

    The term '.\Foo.ps1' 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.
    
    • 编辑:无法工作,因为 PowerShell 正在更改目录,因为 profile.ps1 包含 cd C:\


然后我尝试调用它并指定脚本文件的完整路径,但无论我尝试什么,我都无法让它工作。 我相信我必须引用该路径,因为它包含空格,我需要将参数传递给脚本的文件名也是如此。

  • 迄今为止最好的猜测:

    PowerShell -Command "'C:\Dummy Directory 1\Foo.ps1' 'C:\Dummy Directory 2\File.txt'"
    

    输出错误:

    Unexpected token 'C:\Dummy Directory 2\File.txt' in expression or statement. 
    At line:1 char:136.
    

最佳答案

试试这个:

powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"

关于powershell - 如何从命令行运行 Powershell 脚本并将目录作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13724940/

相关文章:

excel - ComObject Excel.Application(不含 Office 套件)

powershell - 将文件分割成更小的文件,工作脚本,但需要一些调整

powershell - 从 PowerShell 访问 Windows 凭据管理器

regex - PowerShell正则表达式可过滤{{和}}之间的值

powershell - 如何在 Powershell 2.0 中获取驱动器号列表

string - Powershell删除文本文件中的字符串

windows - 删除报表服务器(2014 native 模式)加密 key 和数据 [PowerShell]

powershell - [Powershell] : 2nd Execution of Copy-Item creates subfolder (5. 1.17763.1007)

powershell - 如何在powershell中使用带有空格的$ScriptDir传递msi ArgumentList?

Powershell:在脚本期间将整个命令保存到变量中