68
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.
    
    • 编辑:由于profile.ps1包含PowerShell 正在更改目录而无法正常工作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.
    
4

6 回答 6

61

试试这个:

powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
于 2012-12-05T14:19:53.083 回答
54

您正在调用脚本文件而不是命令,因此您必须使用 -file 例如:

powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"

对于 PS V2

powershell.exe -noexit &'c:\my scripts\test.ps1'

(检查此技术网页面的底部http://technet.microsoft.com/en-us/library/ee176949.aspx

于 2012-12-05T14:31:38.620 回答
27

使用该标志-Command,您可以执行整个 powershell 行,就好像它是 PowerShell 提示符中的命令一样:

powershell -Command "& '<PATH_TO_PS1_FILE>' '<ARG_1>' '<ARG_2>' ... '<ARG_N>'"

这解决了我在 Visual Studio Post-Build 和 Pre-Build 事件中运行 PowerShell 命令的问题。

于 2016-06-13T17:39:57.200 回答
3

在 ps1 文件的顶部添加参数声明

测试.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

结果

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
于 2016-11-07T00:27:13.260 回答
2

将您的代码更改为以下内容:

Function Foo($directory)
    {
        echo $directory
    }

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

然后将其调用为:

powershell -ExecutionPolicy RemoteSigned -File "c:\foo.ps1" "c:\Documents and Settings" "c:\test"

于 2012-12-05T14:54:57.790 回答
0

你有输入并按回车:

PowerShell -命令

于 2020-03-20T13:25:28.093 回答