Home > Enterprise >  Question about Variables in powershell script
Question about Variables in powershell script

Time:05-14

I'm writing a script and I was wondering if there is a way to give a variable for example $a from a script firstscript.ps1 to an other script secondscript.ps1 executed by firstscript.ps1

To clarify what I'm saying :

I exec firstscript.ps1 it does different thing then it launch secondscript.ps1 on a remote computer and i would like the $a from to transfert firstscript.ps1 to secondscript.ps1

NB:I use psexec to exec the secondscript.ps1 remotely to a list of computer with admin right

I could write it in the second one but I want to avoid modification at the bare minimum

CodePudding user response:

then it launch secondscript.ps1 on a remote computer and i would like the $a from to transfert firstscript.ps1 to secondscript.ps1

Assuming you invoke the script remotely using Invoke-Command, pass arguments to the script via the -ArgumentList parameter:

## script1.ps1

# assign value to `$a`
$a = $(...)

# ...

# invoke script2.ps1 on remote machine with $a passed as first argument
Invoke-Command -ComputerName $nameOfRemoteComputer -FilePath path\to\script2.ps1 -ArgumentList $a

Then in script2.ps1, either read the argument value from $args[0]:

## script2.ps1

$a = $args[0] # grab argument value passed by script1.ps1

# work with $a here ...

... or declare a param() block with a parameter that the argument can be bound to:

## script2.ps1
param(
    $a # Let the runtime bind the argument value passed by script1.ps1 to this parameter variable
)

# work with $a here ...
  • Related