Passing a variable to a powershell script via command line

前端 未结 5 1661
醉梦人生
醉梦人生 2020-12-08 00:27

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.

Now I want to change i

相关标签:
5条回答
  • 2020-12-08 00:36

    Make this in your test.ps1, at the first line

    param(
    [string]$a
    )
    
    Write-Host $a
    

    Then you can call it with

    ./Test.ps1 "Here is your text"
    

    Found here (English)

    0 讨论(0)
  • 2020-12-08 00:42

    Passed parameter like below,

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

    .\script_name.ps1 -Name name -Key key

    0 讨论(0)
  • 2020-12-08 00:49

    Declare the parameter in test.ps1:

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

    Run the script from 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"
    

    or,

     powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
    
    0 讨论(0)
  • 2020-12-08 00:54

    Using param to name the parameters allows you to ignore the order of the parameters:

    ParamEx.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"
    
    0 讨论(0)
  • 2020-12-08 01:00

    Here's a good tutorial on Powershell params:

    PowerShell ABC's - P is for Parameters

    Basically, you should use a param statement on the first line of the script

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

    or use the $args built-in variable, which is auto-populated with all of the args.

    0 讨论(0)
提交回复
热议问题