In this article, we will explore how to generate a file and send it to the Midserver first, and then from the Midserver to an SFTP location using a PowerShell script.
1. Plugin Installation on the Mid-Server:
Make your Mid-Server eligible for file transfers to SFTP.
a. Login to the MID Server as the local admin. (DEVMID007 Example)
b. Start PowerShell with admin privileges.
c. Run the command (type it in and press enter)
Install-Module -Name Posh-SSH -Force -Verbose2. Prepare the Powershell Script
Prepare commands based on your requirements.
In my case, I need to drop the entire folder to the SFTP location.
$password = ConvertTo-SecureString 'AddUserName' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('AddPassword', $password)
$SFTPSession = New-SFTPSession -ComputerName secureftp.websiteurl.com -Credential $Credential -AcceptKey -force -warningaction silentlycontinue
$SourceFilePath = "D:\ServiceNow\ServiceNow MID Server MID007\agent\export"
$DestFilePath = "/SpecificFolderOnSFTP/"
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path $SourceFilePath -Destination $DestFilePath -Verbose -Force
Remove-SFTPSession -SFTPSession $SFTPSession
3. Add the script to the "Mid-server Script Files":
Please refer to the attached image.
4. Creating "Run" the Power Shell Script on MidServer
(function execute(inputs, outputs) {
var midServerName = gs.getProperty('MidServerName');
// Push File to SFTP - Create ECC Output Record
var eccQueue = new GlideRecord('ecc_queue');
eccQueue.initialize();
eccQueue.agent = 'mid.server.'+midServerName
eccQueue.topic = 'Command';
eccQueue.queue = 'output';
eccQueue.state = 'ready';
eccQueue.payload = '';
eccQueue.name = "Powershell.exe -File scripts\\PowerShell\\PushToSFTP.ps1";
eccQueue.source = '';
outputs.ecc_queue_created_sys_id = eccQueue.insert();
})(inputs, outputs);
Some Powershell Commands for debugging:
The following script can be directly written to the ecc_queue table.
Queue set to output
State set to ready.
As soon as you create the output, the system processes it and creates an input response. You can then check, understand, and adjust accordingly.
Queue set to output
State set to ready.
As soon as you create the output, the system processes it and creates an input response. You can then check, understand, and adjust accordingly.
# Execute the PowerShell script to push files to SFTP
Powershell.exe -File scripts\PowerShell\PushToSFTP.ps1
# Change directory to lib\x86-32 and list contents
Powershell.exe cd lib\x86-32; ls;
# Change directory to export and list contents
Powershell.exe cd export; ls;
# Delete the specified folder from the Mid Server
Powershell.exe Remove-Item -Path "D:\ServiceNow MID Server DEVMID007\agent\export\SFTPFolderName" -Force
# Change directory to export and delete all .csv files
Powershell.exe cd export; Remove-Item *.csv;
Thank you.
