簡體   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