如何从命令行运行 Powershell 脚本并将目录作为参数传递 [英] How to run a Powershell script from the command line and pass a directory as a parameter

查看:87
本文介绍了如何从命令行运行 Powershell 脚本并将目录作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 的目录中,但结果是:

    Despite Foo.ps1 being in the directory from where I am calling Powershell, this results in:

    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.
    

    • 由于 profile.ps1 包含 cd C:\
    • ,PowerShell 正在更改目录,因此无法工作

      • Wasn't working because PowerShell was changing directory due to profile.ps1 containing cd C:\

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

        • 目前最好的猜测:

        • Best guess so far:

        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 脚本并将目录作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆