通过命令行将变量传递给 powershell 脚本 [英] Passing a variable to a powershell script via command line
问题描述
我是 powershell 的新手,正在尝试自学基础知识.我需要写一个ps脚本来解析一个文件,这已经不是太难了.
I am new to powershell, and trying to teach myself the basics. I need to write a ps script to parse a file, which has not been too difficult.
现在我想更改它以将变量传递给脚本.该变量将是解析字符串.现在,变量将始终是 1 个单词,而不是一组单词或多个单词.
Now I want to change it to pass a variable to the script. that variable will be the parsing string. Now, the variable will always be 1 word, and not a set of words or multiple words.
这看起来非常简单,但对我来说却是一个问题.这是我的简单代码:
This seems uber simple yet is posing a problem for me. Here is my simple code:
$a = Read-Host
Write-Host $a
当我从命令行运行脚本时,变量传递不起作用:
When I run the script from my command line the variable passing doesn't work:
.\test.ps1 hello
.\test.ps1 "hello"
.\test.ps1 -a "hello"
.\test.ps1 -a hello
.\test.ps1 -File "hello"
正如你所看到的,我尝试了很多方法都没有成功,脚本取值并输出它.
As you can see, I have tried many methos with no success, of the script taking the value an outputting it.
脚本确实运行,并等待我输入一个值,当我输入时,它会回显该值.
The script does run, and waits for me to type a value, and when I do, it echos that value.
我只是想让它输出我传入的值,我错过了什么小东西?
I just want it to output my passed in value, what minuscule thing am I missing?
谢谢.
推荐答案
这里有一个关于 Powershell 参数的好教程:
Here's a good tutorial on Powershell params:
基本上,您应该在脚本的第一行使用param
语句
Basically, you should use a param
statement on the first line of the script
param([type]$p1 = , [type]$p2 = , ...)
或使用 $args 内置变量,该变量会自动填充所有参数.
or use the $args built-in variable, which is auto-populated with all of the args.
这篇关于通过命令行将变量传递给 powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!