0

我有以下 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

有人可以指出在脚本块中测试文件是否存在需要什么吗?

谢谢!

4

1 回答 1

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"
于 2017-06-21T17:23:35.090 回答