如何从命令行运行PowerShell脚本并传递目录作为参数

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

Function Foo($directory)
{
    echo $directory
}

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

尽管我从调用Powershell的目录中找到了Foo.ps1文件,但结果却是:

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正在更改目录,因此未能正常工作。


然后我尝试调用指定脚本文件的完整路径,但无论我尝试什么,都无法让它工作。我认为我必须引用路径,因为它包含空格,就像我需要传递一个参数到脚本的文件名一样。

  • 到目前为止最好的猜测:

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.

1
当您从cmd调用powershell时,也可以使用-NoProfile。 - user467384
6个回答

64

试试这个:

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

57

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

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

适用于 PS V2

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

(请查看此 Technet 页面底部 http://technet.microsoft.com/en-us/library/ee176949.aspx


2
Windows PowerShell 1.0 所有者手册已经停用。如需获取最新的 Windows PowerShell 内容,请访问 https://msdn.microsoft.com/en-au/powershell/scripting/core-powershell/console/powershell.exe-command-line-help#-file-filepath-parameters。 - Dave Anderson

30

使用标志-Command,您可以将整个PowerShell命令作为命令在PowerShell提示符中执行:

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

这解决了我在 Visual Studio 后期构建和预构建事件中运行 PowerShell 命令的问题。


3

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

test.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

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"


0

请键入并按回车:

PowerShell -Command


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接