我对PowerShell比较陌生,并且有一个脚本可以读取一个配置文件,该文件会产生一组名称值对,我希望将它们作为参数传递给第二个PowerShell脚本中的函数.
我不知道在设计时将在此配置文件中放置哪些参数,所以就在我需要调用第二个PowerShell脚本时,我基本上只有一个变量具有第二个脚本的路径,第二个脚本变量,它是要传递给路径变量中标识的脚本的参数数组.
因此,包含第二个脚本($ scriptPath)路径的变量可能具有如下值:
"c:\the\path\to\the\second\script.ps1"
Run Code Online (Sandbox Code Playgroud)
包含参数($ argumentList)的变量可能类似于:
-ConfigFilename "doohickey.txt" -RootDirectory "c:\some\kind\of\path" -Max 11
Run Code Online (Sandbox Code Playgroud)
如何从这种状态到使用$ argumentList中的所有参数执行script.ps1?
我希望来自第二个脚本的任何write-host命令对于调用此第一个脚本的控制台是可见的.
我尝试过dot-sourcing,Invoke-Command,Invoke-Expression和Start-Job,但我还没有找到一种不会产生错误的方法.
例如,我认为最简单的第一条路线是尝试按如下方式调用Start-Job:
Start-Job -FilePath $scriptPath -ArgumentList $argumentList
Run Code Online (Sandbox Code Playgroud)
...但是由于此错误而失败:
System.Management.Automation.ValidationMetadataException:
Attribute cannot be added because it would cause the variable
ConfigFilename with value -ConfigFilename to become invalid.
Run Code Online (Sandbox Code Playgroud)
...在这种情况下,"ConfigFilename"是第二个脚本定义的参数列表中的第一个参数,我的调用显然试图将其值设置为"-ConfigFilename",这显然是为了按名称标识参数,没有设定它的价值.
我错过了什么?
编辑:
好的,这是一个名为invokee.ps1的文件中的待调用脚本的模型
Param(
[parameter(Mandatory=$true)]
[alias("rc")]
[string]
[ValidateScript( {Test-Path $_ -PathType Leaf} )]
$ConfigurationFilename,
[alias("e")]
[switch]
$Evaluate,
[array]
[Parameter(ValueFromRemainingArguments=$true)]
$remaining)
function sayHelloWorld()
{
Write-Host "Hello, everybody, the config file is <$ConfigurationFilename>."
if ($ExitOnErrors)
{
Write-Host "I should …Run Code Online (Sandbox Code Playgroud) powershell parameter-passing command-line-arguments invoke-command start-job
我通常有这个命令来运行一些powershell脚本:
& ".\NuGet\NuGet Package and Publish.ps1" -Version $env:appveyor_build_version -NuGet "C:\Tools\NuGet\nuget.exe" -apiKey $env:apiKey
工作正常但脚本在我的服务器本地找到.
我希望这样说:用参数运行这个脚本等等......很好..但脚本位于GIST或某些GitHub公共仓库中.
这可能吗?