Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Save entire command into variable during script

Tags:

powershell

I want to store a command directly inside a variable in a script, and then call that same command later in the script.

I attempted to do it like this:

$command = Invoke-Command -ComputerName $Computer -Credential $Credential -ScriptBlock{(Get-CimInstance Win32_SoftwareFeature -Filter "productname LIKE 'Microsoft SQL Server% %Setup (English)'").ProductName}
Invoke-Expression $command

Problem with that method is the first time the script comes across that first line of code, it attempts to run that code. At that time in the script, I haven't assigned the remaining variables

This is particularly a problem where I am trying to run PSExec in a script. I have about 10 commands that I want to wrap into variables and then call later in various points of the script.

$CreateSymbolicLink = .\PsExec\PsExec.exe \\$computer -u username -p password -accepteula -h -i 1 cmd "/c mklink /D C:\Applications \\server\Share"

Invoke-Expression $CreateSymbolicLink

But when the script runs from the beginning, it actually runs PSExec when the variables haven't been defined, which I'm trying to avoid it from doing.

How can I accomplish this? I've tried using the Set-Variable cmdlet but that also seems to run the command as well, not what I want it to do.

like image 735
Adam Zaloum Avatar asked Oct 12 '25 09:10

Adam Zaloum


1 Answers

Assign the variable as usual like this:

$a = { 
#script block code 
(Get-CimInstance Win32_SoftwareFeature -Filter "productname LIKE 'Microsoft SQL Server% %Setup (English)'").ProductName
} 

then

Invoke-Command -ComputerName $Computer -Credential $Credential -ScriptBlock $a

The other way, is, wrap it all up into a variable itself, similar to the above:

$command = { 
Invoke-Command -ComputerName $Computer -Credential $Credential -ScriptBlock{(Get-CimInstance Win32_SoftwareFeature -Filter "productname LIKE 'Microsoft SQL Server% %Setup (English)'").ProductName}
}

Invoke it like this:

& $command

The first example would be more beneficial for different environments where this can be deployed to, multiple times over, especially, in cases of like, for example,Octopus Deploy, run the script block across multiple machines with tentacles, that is one such example that springs to mind.

like image 96
t0mm13b Avatar answered Oct 15 '25 15:10

t0mm13b