3

If I have the below saved as new.pl, how do I pass $name from the powershell command line to it so I can run and set the variable from PS:

print "Hello, world, from $name.\n";

I tried start-process and using cmd.exe /C but don't really know what is needed.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
geeeeeo
  • 31
  • 2

2 Answers2

3

You'd simply use

perl a.pl $name

This provides the value in @ARGV.

use v5.20;
use warnings;

my ( $name ) = @ARGV;

say "Hello, world, from $name.";
PS> $name = "your friendly neighbourhood Spiderman"
PS> perl a.pl $name
Hello, world, from your friendly neighbourhood Spiderman.

As a one-liner:

perl "-Mv5.20" -e"say qq{Hello, world, from `$ARGV[0].}" $name

If you need to pass arguments while using -n or -p, see How can I process options using Perl in -n or -p mode?

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

I found this answer which says you can use the -s command line switch in order to be able to pass arbitrary data. The example provided in this answer is this:

perl -se 'print "xyz=$xyz\n"' -- -xyz="abc"

The -e switch in this example just allows execution of code from the command line, which isn't necessary in this case because you're running a file, so we can just get rid of it. I'm not experienced with perl and can't find anything on what the -- does. If someone knows feel free to leave a comment and I will add it to the answer, but for now I'll just ignore it because it seems to work without it.

After these modifications, the command above would look something like this:

perl -s new.pl -name="joe"

Pretty simple. Now we can very easily convert this to a PowerShell command. perl is the program being ran, and everything else is arguments. using Start-Process it would look like this:

Start-Process perl -ArgumentList "-s new.pl -name=`"joe`""

Now this does work, but by default Start-Process creates a new window, so it's opening the perl interpreter which just instantly closes because there's nothing telling it to wait. If you want it to print the output to the PowerShell window, you can just use the -NoNewWindow switch.

Start-Process perl -ArgumentList "-s new.pl -name=`"joe`"" -NoNewWindow
Jesse
  • 1,386
  • 3
  • 9
  • 23
  • Setting global variables in a program is not the proper way to provide them with arguments. The program won't even be able to use them without taking extra steps if `use strict;` (or equivalent) is used like it should. – ikegami Jun 23 '22 at 17:41
  • Thanks, i gave this a try but think my perl install and path are messed up as i'm getting win32 errors, i think it wold work as described otherwise. – geeeeeo Jun 23 '22 at 19:22