For years, I have used the cmd/DOS/Windows
shell and passed command-line arguments to batch files. For example, I have a file, zuzu.bat
and in it, I access %1
, %2
, etc. Now, I want to do the same when I call a PowerShell
script when I am in a Cmd.exe shell
. I have a script, xuxu.ps1
(and I've added PS1 to my PATHEXT variable and associated PS1 files with PowerShell). But no matter what I do, I seem unable to get anything from the $args
variable. It always has length 0.
If I am in a PowerShell
shell, instead of cmd.exe
, it works (of course). But I'm not yet comfortable enough to live in the PowerShell environment full time. I don't want to type powershell.exe -command xuxu.ps1 p1 p2 p3 p4
. I want to type xuxu p1 p2 p3 p4
.
Is this possible, and if so, how?
The sample I cannot get to work is trivial, foo.ps1:
Write-Host "Num Args:" $args.Length;
foreach ($arg in $args) {
Write-Host "Arg: $arg";
}
The results are always like this:
C:\temp> foo
Num Args: 0
C:\temp> foo a b c d
Num Args: 0
c:\temp>
This article helps. In particular, this section:
-File
Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.
i.e.
powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3
means run the file myfile.ps1 and arg1 arg2 & arg3 are the parameters for the PowerShell script.