繁体   English   中英

通过命令行将变量传递给 powershell 脚本

[英]Passing a variable to a powershell script via command line

我是 powershell 的新手,并试图自学基础知识。 我需要写一个ps脚本来解析一个文件,这已经不是太难了。

现在我想更改它以将变量传递给脚本。 该变量将是解析字符串。 现在,变量将始终是 1 个单词,而不是一组单词或多个单词。

这看起来非常简单,但对我来说却是一个问题。 这是我的简单代码:

$a = Read-Host
Write-Host $a

当我从命令行运行脚本时,变量传递不起作用:

.\test.ps1 hello
.\test.ps1 "hello"
.\test.ps1 -a "hello"
.\test.ps1 -a hello
.\test.ps1 -File "hello"

正如您所看到的,我尝试了很多方法都没有成功,脚本取值并输出它。

该脚本确实运行,并等待我输入一个值,当我输入时,它会回显该值。

我只是想让它输出我传入的值,我错过了什么微不足道的东西?

谢谢你。

在你的 test.ps1 中做这个,在第一行

param(
[string]$a
)

Write-Host $a

然后你可以用

./Test.ps1 "Here is your text"

这里找到( 英文

这是一个关于 Powershell 参数的好教程:

PowerShell ABC's - P 代表参数

基本上,您应该在脚本的第一行使用param语句

param([type]$p1 = , [type]$p2 = , ...)

或使用 $args 内置变量,它会自动填充所有参数。

在 test.ps1 中声明参数:

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

从 Run OR Windows Task Scheduler 运行脚本:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

要么,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

传递参数如下,

Param([parameter(Mandatory=$true,
   HelpMessage="Enter name and key values")]
   $Name,
   $Key)

.\\script_name.ps1 -Name name -Key key

使用 param 命名参数允许您忽略参数的顺序:

参数表达式.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM