Not working when using variables in script block
juriggs opened this issue · comments
EDIT: Looks like having parentheses around my command caused it to fail. Took the parenths out, and everything worked.
Trying this:
$var1 = "C:\Users<user><file>"
Invoke-CommandAs -Computername Comp1 -scriptblock {param($var1)(Get-Item -Force $var1)} -ArgumentList $var1 -AsSystem
Nothing returns...
If I do the normal Invoke-Command:
Invoke-Command -Computername DEN-DATA-RES01 -scriptblock {param($var1)(Get-Item -Force $var1)} -ArgumentList $var1 -AsSystem
it returns the output
I was struggling with this yesterday. Burnt the morning trying to make it work. I found that the variables weren't being expanded inside my script block. Then i found this page from The Scripting Guy about declaring the script block like below: (in case you can't see them, there are backticks to the left of the quotes around $NewFolderName )
$ScriptBlock = "takeown /f "$NewFolderName
" /r /a /d y"
$SB = [ScriptBlock]::Create($ScriptBlock)
Invoke-Commandas -scriptblock $SB -AsSystem -Verbose
Please ignore the context if what was going on here, it's the method of creating the script block that's important.
Please see this page for more details:
https://devblogs.microsoft.com/scripting/variable-substitution-in-a-powershell-script-block/
Thanks for your comment. Is this just an FYI? Or is there a bug with the implementation within the module?
Purely an FYI in case anyone else comes across this. Just seems like a Powershell quirk.
Thanks very much for writing this module; it’s massively helpful and (as far as I’ve seen) really solid! It’s the best way I’ve found to execute as System when PSExec isn’t an option. Great work!