none
Code works in PowerShell ISE but not in PowerShell console window RRS feed

  • Question

  • I need to upload a file to a web server (to a Jira server, actually). The below code works perfectly when the script is run in PowerShell ISE:

        $WebClient = new-object System.Net.WebClient
        $WebClient.Headers.Add("Authorization", "Basic " + $AuthStr)
        $WebClient.Headers.Add("X-Atlassian-Token", "nocheck")
        $WebClient.UploadFile($BasePath + "/attachments", $AttachmentFile) >$null

    However, the same code with the same data throws an error when executed in a usual PowerShell console window:

    Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
    At C:\Temp\Qualys\ProcessWeeklyReport.ps1:69 char:5
    +     $WebClient.UploadFile($BasePath + "/attachments", $AttachmentFile ...
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : WebException

    I was unable to obtain a more detailed error message. No PowerShell profiles have been created, the Powershell environment is in its default state.

    Can someone suggest where to dig?


    Evgeniy Lotosh // MCSE: Server infrastructure, MCSE: Messaging

    Monday, October 21, 2019 5:27 PM

Answers

  • Found it. $AttachmentFile string variable contains file name. However, this is only the name of file without any path. This file is located in the script folder. Due to some reason UploadFile method can't find this file if executed in the standalone console. The full path to the file (including folder path) should be specified to make it work properly.

    The above code should be modified to work in both in ISE and the console:

    $WebClient = new-object System.Net.WebClient
    $WebClient.Headers.Add("Authorization", "Basic " + $AuthStr)
    $WebClient.Headers.Add("X-Atlassian-Token", "nocheck")
    $WebClient.UploadFile($BasePath + "/attachments", (Get-Location).Path + "\" + $AttachmentFile)



    Evgeniy Lotosh // MCSE: Server infrastructure, MCSE: Messaging

    • Marked as answer by Evgeniy Lotosh Thursday, October 24, 2019 5:23 PM
    Thursday, October 24, 2019 5:23 PM