脚本抱怨在找不到文件时找不到该文件

时间:2016-09-15 13:39:12

标签: powershell error-handling windows-7

我在登录脚本中运行以下函数,该脚本检查用户是否具有当前版本的IT Self Help.exe。如果当前版本不存在,则应将其从$appsource文件夹复制到桌面上:

function UrgentSupportApp {
    $ErrorActionPreference = "Stop"
    trap {Log-Error $_ $MyInvocation.MyCommand; Return}

    $desktop = $env:USERPROFILE + '\Desktop\'
    $apptarget = $desktop + 'IT Self Help.exe'
    $appsource = '\\file\Administration\Unused\Apps\IT Support App\IT Self Help.exe'

    # Remove the old version of the app "IT Help Request.exe"
    $oldapps = Get-ChildItem $desktop -Filter *"Help Request.exe"
    if ($oldapps.count -gt 0) {Remove-Item $oldapps.PSPath -Force}

    # Copy the new version over if it is not already present
    $currentversion = (Get-Command $appsource).FileVersionInfo.FileVersion 
    if (Test-Path $apptarget) {
        if ((Get-Command $apptarget).FileVersionInfo.FileVersion -ne $currentversion) {
            Copy-Item $appsource $desktop -Force  ##### Line 981 #####
        }
    } else {
        Copy-Item $appsource $desktop -Force
    }
}
function Log-Error {
    param (
        $error,
        [string]$sub,
        $detail
    )
    $ErrorActionPreference = "Stop"
    trap {Log-Error $_ $MyInvocation.MyCommand; Return}

    $filename = "\\file\administration\Unused\LogonScriptErrors\$username - $sub - $computername - $(Get-Date -Format ddMMyyyy-HHmmss).log"

    New-Item $filename -ItemType File -Value "Message: `r`n`t $($error.Exception.Message) `r`n `r`nPosition: `r`n`t $($error.InvocationInfo.PositionMessage) `r`n `r`nSub: `r`n`t $sub `r`n `r`nDetail: `r`n`t $detail"
}

对于几个用户,我看到这个错误来自第981行,char 22(见上面的评论):

Could not find file 'C:\Users\USER.NAME\Desktop\IT Self Help.exe'. 
At \\DC\NETLOGON\mainlogon.ps1:981 char:22
+             Copy-Item <<<<  $appsource $desktop -Force

然而

  • 可以找到该文件,因为它通过fisrt If条件If (Test-Path $apptarget)。{/ li>
  • 如果找不到该文件,为什么脚本会在该行上抱怨,我们甚至都没有找到它?

试图告诉我这个错误是什么?如果找不到该文件,那么该脚本肯定会继续进入Else语句

0 个答案:

没有答案