Home > Software engineering >  Extract file names from Posh-SSH Get-SFTPChildItem output in PowerShell
Extract file names from Posh-SSH Get-SFTPChildItem output in PowerShell

Time:12-26

I want to take this part

REGISTRATION_ELI_20221222_071008.csv

from this PowerShell output of Posh-SSH Get-SFTPChildItem

Name REGISTRATION_ELI_20221222_071008.csv, Length 0, User ID 1142, Group ID 1220, Accessed 12/21/2022 3:00:47 PM, Modified 12/21/2022 3:00:47 PM

How can I get it?

#Date
$time = (Get-Date).ToString("yyyyMMdd") 

#Setting credentials for the user account
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("gomgom", $password)

$SFTPSession = New-SFTPSession -ComputerName 172.16.xxx.xxx -Credential $Credential -AcceptKey

# Set local file path and SFTP path
$LocalPath = "D:\WORK\Task - Script\20221010 - AJK - ITPRODIS380 - upload file csv ke sql server\csvfile"

$FilePath = Get-SFTPChildItem -SessionId $SFTPSession.SessionId "/Home Credit/Upload/" | Select-String -Pattern "REGISTRATION_ELI_$([datetime]::Now.toString('yyyyMMdd'))" 
$FilePath
Remove-SFTPSession $SFTPSession -Verbose

CodePudding user response:

Do not parse the name from the string dump of the file object.

The Posh-SSH Get-SFTPChildItem returns SSH.NET SftpFile, which has Name attribute:

$FilePath.Name

(though then the $FilePath is actually a confusing variable name, as it's an object, not a mere path string)

CodePudding user response:

You can dig into the Regex library and extract it out using Regex

$test = "Name REGISTRATION_ELI_20221222_071008.csv, Length 0, User ID 1142, Group ID 1220, Accessed 12/21/2022 3:00:47 PM, Modified 12/21/2022 3:00:47 PM"
$matches = [regex]::Match($test,"REGISTRATION. \.csv")
$Matches.Value

CodePudding user response:

$FilePath | Select-String -Pattern 'Name\s(.*?),' -AllMatches| Foreach-Object {$.Matches} | Foreach-Object {$.Groups[1].Value}

  • Related