我有一个用于压缩文件的 powershell 脚本,但遇到了一些问题。我的脚本的简化版本是:
function MyFunction([__ComObject] $zipFile)
{
if(test-path($zipFile.Self.Path))
{
"Zip path found in MyFunction: " + $zipFile.Self.Path
}
else
{
"Zip path not found in MyFunction: " + $zipFile.Self.Path
}
# Check path directly
if(test-path("C:\zips\july2013.zip"))
{
"Direct zip path found in MyFunction: " + $zipFile.Self.Path
}
else
{
"Direct zip path not found in MyFunction: " + $zipFile.Self.Path
}
}
$zipfilepath = "C:\zips\july2013.zip"
if(-not (test-path($zipfilepath)))
{
set-content $zipfilepath ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilepath).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilepath)
if( (test-path($zipPackage.Self.Path)))
{
"Zip exists: " + $zipPackage.Self.Path
}
else
{
"Zip does not exist: " + $zipPackage.Self.Path
}
MyFunction $zipPackage
如果 C:\zips\july2013.zip 在我运行脚本之前存在,或者我通过打开 powershell 进行调试来运行它,我会得到(如我所料):
Zip exists: C:\zips\july2013.zip
Zip path found in MyFunction: C:\zips\july2013.zip
Direct zip path found in MyFunction: C:\zips\july2013.zip
但是,如果文件不存在 C:\zips\july2013.zip 并且我在不打开 powershell 的情况下运行它(即右键单击“使用 powershell 运行”),我会得到:
Zip exists: C:\zips\july2013.zip
Zip path not found in MyFunction: C:\zips\july2013.zip
Direct zip path not found in MyFunction: C:\zips\july2013.zip
我是powershell的新手,有什么想法吗?