PowerShell Test-Path无法在scriptblock中运行

时间:2017-06-21 17:05:51

标签: powershell io scriptblock

我有以下PowerShell代码,用于测试脚本块中是否存在文件:

$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

当我运行它时,我得到以下输出,表明该文件存在于主执行中但不存在于脚本块中。

Main filename MyFile.xml Exists? -> True
Scriptblock filename MyFile.xml Exists? -> False

有人可以说明在脚本块中测试文件存在需要什么吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

作为最佳实践,您应该包括要测试的文件的完整路径,而不是依赖于当前目录(如果您在不同的用户上下文下运行脚本,则可能会有所不同)。

$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"