I have the following PowerShell code that tests if a file exists within a script block:
$scriptblock =
{
Param($filename)
return "Scriptblock filename $filename Exists? -> $(Test-Path $filename)"
}
$myFilename = "MyFile.xml"
Write-Host "Main filename $myFilename Exists? -> $(Test-Path $myFilename)"
$job = Start-Job -Name "myJob" -ScriptBlock $scriptBlock -ArgumentList $myFilename
$result = Receive-Job -Name "myJob"
Write-Host $result
When I run it I get the following output indicating the file exists in the main execution but not in the script block.
Main filename MyFile.xml Exists? -> True
Scriptblock filename MyFile.xml Exists? -> False
Can someone please indicate what is needed to test for file existence in a script block?
Thanks!
As a best practice, you should probably be including the full path to the file you want tested, rather than relying on the current directory (which can vary if you run the script under a different user context).
$scriptblock = {
param($filename)
"Scriptblock filename $filename Exists? -> $(Test-Path $filename)"
}
$myFilename = "C:\Temp\MyFile.xml"
"Main filename $myFilename Exists? -> $(Test-Path $myFilename)"
Start-Job -Name "myJob" -ScriptBlock $scriptBlock -ArgumentList $myFilename
Receive-Job -Name "myJob"