subverts_rule subverts_rule - 4 months ago 11
PowerShell Question

Specify NON-hardcoded path and filename in a scriptblock?

Ok I feel spechul for even asking, but I have tried several iterations of this and nothing has worked except hard coding the scriptname in the Scriptblock statement, which is unacceptable.

Here is the code that works, hard coded, unacceptable....

$Scriptblock = { C:\Scripts\Path1\ScriptName.ps1 -arguement0 $args[0] -arguement1 $args[1] }
Start-Job -ScriptBlock $Scriptblock -ArgumentList $argue0, $argue1 | Out-Null


Ive tried this, and it doesn't work...

$loc = (Get-Location).Path
Set-Location -Path $loc


And this....

$rootpath = $MyInvocation.MyCommand.Path.Substring(0, ($MyInvocation.MyCommand.Path).LastIndexOf("\"))
Set-Location -Path $rootpath


And this....

$rootpath = $MyInvocation.MyCommand.Path.Substring(0, ($MyInvocation.MyCommand.Path).LastIndexOf("\"))
$scriptFilename = $([string]::Format("{0}\ScriptName.ps1", $rootpath))
$sb = $([string]::Format("{0} -arguement0 $args[0] -arguement1 $args[1]", $scriptFilename))
$Scriptblock = { $sb }
Start-Job -ScriptBlock $Scriptblock -ArgumentList $argue0, $argue1 | Out-Null


Nothing else has worked except the first code above with hardcoded path and script name - I know it has to be something stupid I am missing - help me fix stoopid please! ;-)

Answer

In your last example, this line:

$ScriptBlock = { $sb }

simply creates a scriptblock with a string inside it. Change it to:

$ScriptBlock = [scriptblock]::Create($sb)