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.
$command = { Invoke-Command -ComputerName $Computer -Credential $Credential -ScriptBlock { (Get-CimInstance Win32_SoftwareFeature -Filter "productname LIKE 'Microsoft SQL Server% %Setup (English)'").ProductName }and& $command.