.net - Powershell ScriptBlock Not Executing -
i'm trying execute code on remote machine using invoke-command
. part of method includes scriptblock
parameter, , sense i'm not doing correctly.
first tried create method in script, looked this:
param([string] $filename) function validatepath( $file, $filetype = "container" ) { $fileexist = $null if( -not (test-path $file -pathtype $filetype) ) { throw "the path $file not exist!" $fileexist = false } else { echo $filename found! $fileexist = true } return $fileexist } $responseobject = invoke-command -computername minint-ou9k10r -scriptblock{validatepath($filename)} -asjob $result = receive-job -id $responseobject.id echo $result
to call this, .\myscriptname.ps1 -filename c:\file\to\test
. script execute, not call function.
then thought maybe should put function new script. looked like:
file 1:
$responseobject = invoke-command -computername minint-ou9k10r -scriptblock { .\file2.ps1 -filename c:\something } -asjob $result = receive-job -id $responseobject.id echo $result
file 2:
param([string] $filename)
neither of these approaches execute function , i'm wondering why; or, need make work.
function validatepath( $file, $filetype = "container" ) { $fileexist = $null if( -not (test-path $file -pathtype $filetype) ) { throw "the path $file not exist!" $fileexist = false } else { echo $filename found! $fileexist = true } return $fileexist }
that's because invoke-command executes code in script block on remote computer. validatepath function not defined on remote computer, , script file file2.ps1 not exist there. there nothing gives remote computer access code in script executes invoke-command or files on computer on script running. you'd need either copy file2.ps1 remote computer, or provide unc path share on computer file available, or put contents of validatepath function in script block. sure change instances of $file $filename or vice versa , adapt code run interactively, example you'd eliminate $fileexist , return statement.
to put path-validating code in scriptblock gets passed remote computer, you'd this:
$scriptblock = @" if (-not (test-path $filename -pathtype 'container') ) { throw "the path $file not exist!" } else { echo $filename found! } "@ $responseobject = invoke-command -computername minint-ou9k10r -scriptblock{$scriptblock} -asjob
n.b. make sure "@ not indented. must @ beginning of line.
btw, although moot, what's point of setting variable after throw statement? once throw error, function terminates. $fileexist = false
never execute under circumstances. wanted use write-error.
Comments
Post a Comment