OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

PowerShell script runs with Windows PowerShell ISE but not with Windows PowerShell [closed]

  • Thread starter Thread starter Brian
  • Start date Start date
B

Brian

Guest
I have a PowerShell script to upload any files in local folders to a remote directory on a sftp server. Here's the script:

Code:
# Set variables for local paths and remote path
$remotePath = "/myRemotePath/here/"
$localPaths = @(
    "D:\local\myfirstlocalfolder",
    "D:\local\mysecondlocalfolder"
)

# Initialize an array to hold watchers
$global:watchers = @()

# Function to handle the file created event
function HandleFileCreated {
    param(
        [string]$localFilePath
    )

    Write-Host "File created: $localFilePath"

    # Specify WinSCP assembly path
    $assemblyPath = "C:\Program Files (x86)\WinSCP"
    Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "hostname.eu"
        UserName = "username"
        Password = "password"
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxx..."
    }

    $session = New-Object WinSCP.Session

    try {
        # Get the local path from the event args
        $localPath = Split-Path -Path $localFilePath

        # Calculate remote file path based on original local path and remote base path
        $relativePath = $localFilePath.Substring($localPath.Length + 1)
        $remoteFilePath = $remotePath + $relativePath.Replace("\", "/")
        Write-Host "Remote path: $remoteFilePath"

        # Connect to the SFTP server
        $session.Open($sessionOptions)

        # Upload the file to the remote path
        $transferResult = $session.PutFiles($localFilePath, $remoteFilePath)
        $transferResult.Check()

        Write-Host "Upload of $localFilePath succeeded"
    }
    catch {
        Write-Host "Error: $($_.Exception.Message)"
    }
    finally {
        # Disconnect and dispose the session
        $session.Dispose()
    }
}

# Loop through each local path and create a FileSystemWatcher
foreach ($localPath in $localPaths) {
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = $localPath
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $false  # Adjust based on your needs
    $watcher.EnableRaisingEvents = $true

    # Generate a unique event identifier based on the local path
    $watcherEventName = "FileCreated_" + [System.Guid]::NewGuid().ToString()
    
    # Register the event handler for file creation
    Register-ObjectEvent $watcher Created -SourceIdentifier $watcherEventName -Action {
        $eventArgs = $EventArgs[1]
        $localFilePath = $eventArgs.FullPath
        HandleFileCreated -localFilePath $localFilePath
    }

    # Add watcher to the global watchers array
    $global:watchers += $watcher
}

# Keep the script running indefinitely
while ($true) {
    Start-Sleep -Seconds 5
}

This script is running when I open it in Windows PowerShell ISE and press Play but it's not working in Windows PowerShell. The only thing that I see is the FileSystemWatcher with all the folders that need to be watched. When I put a file in one of these local folders nothing happens and I don't see anything on the command line. This do work in PowerShell ISE.

I tried running the script as administrator but this didn't help.

Why is this working in PowerShell ISE but not in the normal PowerShell?
<p>I have a PowerShell script to upload any files in local folders to a remote directory on a sftp server. Here's the script:</p>
<pre><code># Set variables for local paths and remote path
$remotePath = "/myRemotePath/here/"
$localPaths = @(
"D:\local\myfirstlocalfolder",
"D:\local\mysecondlocalfolder"
)

# Initialize an array to hold watchers
$global:watchers = @()

# Function to handle the file created event
function HandleFileCreated {
param(
[string]$localFilePath
)

Write-Host "File created: $localFilePath"

# Specify WinSCP assembly path
$assemblyPath = "C:\Program Files (x86)\WinSCP"
Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "hostname.eu"
UserName = "username"
Password = "password"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxx..."
}

$session = New-Object WinSCP.Session

try {
# Get the local path from the event args
$localPath = Split-Path -Path $localFilePath

# Calculate remote file path based on original local path and remote base path
$relativePath = $localFilePath.Substring($localPath.Length + 1)
$remoteFilePath = $remotePath + $relativePath.Replace("\", "/")
Write-Host "Remote path: $remoteFilePath"

# Connect to the SFTP server
$session.Open($sessionOptions)

# Upload the file to the remote path
$transferResult = $session.PutFiles($localFilePath, $remoteFilePath)
$transferResult.Check()

Write-Host "Upload of $localFilePath succeeded"
}
catch {
Write-Host "Error: $($_.Exception.Message)"
}
finally {
# Disconnect and dispose the session
$session.Dispose()
}
}

# Loop through each local path and create a FileSystemWatcher
foreach ($localPath in $localPaths) {
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false # Adjust based on your needs
$watcher.EnableRaisingEvents = $true

# Generate a unique event identifier based on the local path
$watcherEventName = "FileCreated_" + [System.Guid]::NewGuid().ToString()

# Register the event handler for file creation
Register-ObjectEvent $watcher Created -SourceIdentifier $watcherEventName -Action {
$eventArgs = $EventArgs[1]
$localFilePath = $eventArgs.FullPath
HandleFileCreated -localFilePath $localFilePath
}

# Add watcher to the global watchers array
$global:watchers += $watcher
}

# Keep the script running indefinitely
while ($true) {
Start-Sleep -Seconds 5
}
</code></pre>
<p>This script is running when I open it in Windows PowerShell ISE and press Play but it's not working in Windows PowerShell.
The only thing that I see is the FileSystemWatcher with all the folders that need to be watched.
When I put a file in one of these local folders nothing happens and I don't see anything on the command line.
This do work in PowerShell ISE.</p>
<p>I tried running the script as administrator but this didn't help.</p>
<p>Why is this working in PowerShell ISE but not in the normal PowerShell?</p>
Continue reading...
 
Top