How do I input paramters into a Jenkins perl script from command line? - perl

Background
I am running a Jenkns Job, called Job A, that feeds its build parameters into a perl script, called ScriptA.pl, in the following format below:
#Check the input params
my $PARAM1 = $ENV{ "PARAM1" };
my $PARAM2 = $ENV{ "PARAM2" };
.....more params fed in the same way
if ( $PARAM1 eq "" ) {
print "PARAM1 is a required parameter.\n";
exit 1;
}
if ( $PARAM2 eq "" ) {
print "PARAM2 is a required parameter.\n";
exit 1;
}
.....more param checks done in the same way
###Script then runs a bunch of execution statements####
Problem
I am trying to run this script from Linux command line in cshell in the following way to test that the execution component works:
/% ScriptA.pl jetFuel steelBeams
And it thinks that no parameters have been entered, since this error is returned
PARAM1 is a required parameter.
Question
How do I properly input Jenkins parameters into a Jenkins script from command line?

If you can't modify the Perl script so it reads command-line parameters (which would improve its general usability to boot), maybe create a simple wrapper script:
#/bin/sh
env PARAM1="$1" PARAM2="$2" perl ScriptA.pl
(Yes, sh. Nobody should use csh for anything in 2019.)

Related

Perl occur error when use lib

I have a weird problem, I called a CMD batch script, then the batch script called a perl script
The C# launch process
//
// Launch process.
//
string path = System.IO.Directory.GetCurrentDirectory();
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = fileName,
Arguments = arguments,
WorkingDirectory = workingDirectory,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process process = Process.Start(startInfo);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
The batch script:
"%PerlFolder%\perl.exe" "%CodeFolder%\test.pl"
the test.pl
#!/usr/bin/perl
use strict;
#...
#code
foreach $key (keys(%ENV)) {
printf("%-10.10s: $ENV{$key}\n", $key);
}
but it occurs an error when use the lib, I can't catch the error since it occurs include library(compile) before execute ,it seems like it don't found the lib, so I replace it with absolute path
use lib "C:/Program Files (x86)/perl/lib/strict.pm";
but it still not work, anyone know how to fix this?

Perl to exec a program with arguments containing "#"

Am a newbie in Perl and need help with a small problem
Situation:
I have to execute a command line program through perl.
The arguments to this command line are email addresses
These email addresses are passed to me through another module.
Problem:
I have written the code to create the argument list from these email addresses but am having problem in running exec().
NOTE: If I pass hardcoded strings with escaped "#" character to the exec() as command args,it works perfectly.
Sub creating cmd args map
sub create_cmd_args {
my($self, $msginfo) = #_;
my #gd_args_msg = ('--op1');
my $mf = $msginfo->sender_smtp;
$mf =~ s/#/\\#/ig; ## Tried escaping #, incorrect results.
push #gd_args_msg, '-f="'.$mf.'"';
for my $r (#{$msginfo->per_recip_data}) {
my $recip = $r->recip_addr_smtp;
$recip =~ s/#/\\#/ig; ## Tried escaping #, incorrect results.
push #gd_args_msg, '-r="'.($recip).'"';
}
return #gd_args_msg;
}
Sub that uses this args map to exec the program
sub check {
my($self, $msginfo) = #_;
my $cmd = $g_command;
my #cmd_args = create_cmd_args($self, $msginfo);
exec($cmd, #cmd_args); ### ******* fails here
}
Sample run:
INPUT:
sender_smtp: <ashish#isthisreal.com>
receiver_smtp: <areyouarealperson#somedomain.com>
Could someone please guide me what is wrong here?
As an argument to a command in the shell,
-f="<ashish#isthisreal.com>"
causes the the string
-f=<ashish#isthisreal.com>
to be passed to the program. Your program passes
-f="<ashish\#isthisreal.com>"
to the program. The problem isn't the #; the problem is the " and \ you are adding.
my $mf = $msginfo->sender_smtp;
push #gd_args_msg, "-f=$mf"; # Assuming $mf is <ashish#isthisreal.com>
If you look at the post at Trying to convert Perl to PHP and the code within the md5sum implementation that calls the command line you will see an approach that will save you from needing to worry about escaping characters.

How to retrieve a parameter passed to a perl script using system?

I am using:
system($script, #my_args);
So, I have this code in script.pl file:
my $script = "anotherScript.pl";
#my_args = ("anArgument");
system($script, #my_args);
In anotherScript.pl file, how can I retrieve the arguments in #my_args?
Arguments are received in #ARGV

Send request parameters when calling a PHP script via command line

When you run a PHP script through a browser it looks something like
http://somewebsite.com/yourscript?param1=val1&param2=val2.
I am trying to achieve the same thing via command line without having to rewrite the script to accept argv instead of $_REQUEST. Is there a way to do something like this:
php yourscript.php?param1=val1&param2=val2
such that the parameters you send show up in the $_REQUEST variable?
In case you don't want to modify running script, you can specify parameters using in -B parameter to specify code to run before the input file. But in this case you must also add -F tag to specify your input file:
php -B "\$_REQUEST = array('param1' => 'val1', 'param2' => 'val2');" -F yourscript.php
I can't take credit for this but I adopted this in my bootstrap file:
// Concatenate and parse string into $_REQUEST
if (php_sapi_name() === 'cli') {
parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);
}
Upon executing a PHP file from the command line:
php yourscript.php param1=val1 param2=val2
The above will insert the keys and values into $_REQUEST for later retrieval.
No, there is no easy way to achieve that. The web server will split up the request string and pass it into the PHP interpreter, who will then store it in the $_REQUEST array.
If you run from the command line and you want to accept similar parameters, you'll have to parse them yourself. The command line has completely different syntax for passing parameters than HTTP has. You might want to look into getopt.
For a brute force approach that doesn't take user error into account, you can try this snippet:
<?php
foreach( $argv as $argument ) {
if( $argument == $argv[ 0 ] ) continue;
$pair = explode( "=", $argument );
$variableName = substr( $pair[ 0 ], 2 );
$variableValue = $pair[ 1 ];
echo $variableName . " = " . $variableValue . "\n";
// Optionally store the variable in $_REQUEST
$_REQUEST[ $variableName ] = $variableValue;
}
Use it like this:
$ php test.php --param1=val1 --param2=val2
param1 = val1
param2 = val2
I wrote a short function to handle this situation -- if command line arguments are present and the $_REQUEST array is empty (ie, when you're running a script from the command line instead of though a web interface), it looks for command line arguments in key=value pairs,
Argv2Request($argv);
print_r($_REQUEST);
function Argv2Request($argv) {
/*
When $_REQUEST is empty and $argv is defined,
interpret $argv[1]...$argv[n] as key => value pairs
and load them into the $_REQUEST array
This allows the php command line to subsitute for GET/POST values, e.g.
php script.php animal=fish color=red number=1 has_car=true has_star=false
*/
if ($argv !== NULL && sizeof($_REQUEST) == 0) {
$argv0 = array_shift($argv); // first arg is different and is not needed
foreach ($argv as $pair) {
list ($k, $v) = split("=", $pair);
$_REQUEST[$k] = $v;
}
}
}
The sample input suggested in the function's comment is:
php script.php animal=fish color=red number=1 has_car=true has_star=false
which yields the output:
Array
(
[animal] => fish
[color] => red
[number] => 1
[has_car] => true
[has_star] => false
)

Calling a local function from a dot sourced file

I have a main script that I am running. What it does is read through a directory filled with other powershell scripts, dot includes them all and runs a predefined method in each made up of the first portion of the dot delimited file name. Example:
Run master.ps1
Master.ps1 dot sources .\resource\sub.ps1
Sub.ps1 has defined a function called 'dosub'
Master.ps1 runs 'dosub' using Invoke-Expression
Also defined in sub.ps1 is the function 'saysomething'. Implemented in'dosub' is a call to 'saysomething'.
My problem is I keep getting the error:
The term 'saysomething' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and
try again.
Why can't the method 'dosub' find the method 'saysomething' which is defined in the same file?
master.ps1:
$handlersDir = "handlers"
$handlers = #(Get-ChildItem $handlersDir)
foreach ( $handler in $handlers ) {
. .\$handlersDir\$handler
$fnParts = $handler.Name.split(".")
$exp = "do" + $fnParts[0]
Invoke-Expression $exp
}
sub.ps1:
function saysomething() {
Write-Host "I'm here to say something!"
}
function dosub() {
saysomething
Write-Host "In dosub!"
}
Your code works on my system. However you can simplify it a bit:
$handlersDir = "handlers"
$handlers = #(Get-ChildItem $handlersDir)
foreach ( $handler in $handlers )
{
. .\$handlersDir\$handler
$exp = "do" + $handler.BaseName
Write-Host "Calling $exp"
& $exp
}
Note the availability of the BaseName property. You also don't need to use Invoke-Expression. You can just call the named command ysing the call (&) operator.
What you have given works as needed. You probably don't have the directories etc proper on your machine. Or you are running something else and posting a different ( working!) code here.
You can also make following corrections:
. .\$handlersDir\$handler
instead of above you can do:
. $handler.fullname
Instead the splitting of the filename you can do:
$exp = "do" + $handler.basename