我有以下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
有人可以指出在脚本块中测试文件是否存在所需的内容吗?
谢谢!
作为最佳实践,您可能应该包含要测试的文件的完整路径,而不是依赖于当前目录(如果您在不同的用户上下文中运行脚本,该目录可能会有所不同(。
$scriptblock = {
param($filename)
"Scriptblock filename $filename Exists? -> $(Test-Path $filename)"
}
$myFilename = "C:TempMyFile.xml"
"Main filename $myFilename Exists? -> $(Test-Path $myFilename)"
Start-Job -Name "myJob" -ScriptBlock $scriptBlock -ArgumentList $myFilename
Receive-Job -Name "myJob"