Reputation: 75
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.
Upvotes: 4
Views: 10011
Reputation: 34592
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.
Upvotes: 9