Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

New-WebServiceProxy don't work on console only on ISE


This is a sample of my code:

    Add-Type -AssemblyName PresentationFramework

    Get-Content "$PSScriptRoot\config.ini" | ForEach-Object -Begin {$config=@{}} -Process {$store = [regex]::split($_,'='); if(($store[0].CompareTo("") -ne 0) -and ($store[0].StartsWith("[") -ne $True) -and ($store[0].StartsWith("#") -ne $True)) {$config.Add($store[0], $store[1])}}

    $folder = $config.Get_Item("CSVFolder")
    $filter = $config.Get_Item("CSVFile")
    $uri = $config.Get_Item("WebServiceUri")

    Function Register-Watcher {
        $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
            IncludeSubdirectories = $false
            EnableRaisingEvents = $true
        }

        $changeAction = {

            $path = $Event.SourceEventArgs.FullPath
            $name = $Event.SourceEventArgs.Name
            $changeType = $Event.SourceEventArgs.ChangeType
            $timeStamp = $Event.TimeGenerated   

            $ConWebSrv = New-WebServiceProxy -Uri $uri
            $rescode = 0
            $resreason = 0

            $get = Get-Content -Path $path -Last 1
            $artnbr,$barc,$desc,$pu,$qtypu,$meanval,$mittelw,$free1,$free2,$free3,$lenght,$width,$height,$lengthuni,$volume,$voluni,$weight,$weightuni,$timest = $get.split(";")

            $CommWebSrv = $ConWebSrv.setItemDims($artnbr,$width,$lenght,$height,$weight,$weight,"EA","KG","CM","KHT",[ref]$rescode,[ref]$resreason)

            $msgBoxInput = [System.Windows.MessageBox]::Show("Nova leitura detectada. Pretende comunicar?","","YesNo", "Information")
            switch  ($msgBoxInput) {

                   "Yes" {write-host "Yes $artnbr"}
                   "No" {write-host "No"}
            }
        }

        Register-ObjectEvent $Watcher "Changed" -Action $changeAction
    }
Register-Watcher

I ended the script and everything is ok on ISE, code runs without any problem. But when I run it at console anything happens when I update the CSV file. I found the problem, it is on $ConWebSrv = New-WebServiceProxy -Uri $uri. If I comment the code out, it runs without problem on console.

Attention: If you copy and paste on console it works, try with .ps1 file.


Solution

  • Solved the problem. Variables of the of the script block $changeaction need to be inside the that scriptblock.