简体   繁体   中英

Get array based on another array

I need to take a CSV file and then create many files out of that in different formats depending on the account number. The account numbers I need are in other files with no other fields (I need to pad them to match). This is just one below.

I know I can cycle through using foreach, but was trying to avoid that. This gives no error, but doesn't work even though I know there are matches.

$sms_accts = import-csv -path "H:\scrap\Positive Pay Feeds\sms_accounts.txt"
$input_file = import-csv -path "H:\scrap\Positive Pay Feeds\CNVDC939.POSITIVE PAY ISSUES.txt"

$sms_accts = $sms_accts  | Select-Object @{Name="Acct";Expression={$_.Acct.PadLeft(11,"0")}}

$to_sms_file = $input_file  | where-object { $sms_accts -contains ($_.ACCOUNT_NUMBER.PadLeft(11,"0"))  }

$to_sms_file

It returns nothing.

Sample file below.

sms_accounts.txt:

Acct
12345678
23456789


Positive Pay:
    "SPONSOR_BANK_ID","BE_CLIENT_ID","COMPANY_NAME","ACCOUNT_NUMBER","SERIAL","AMOUNT","PAYEE","ISSUE_TYPE","STATUS","ENTRY_DATE","ISSUE_DATE"
    "100741","1004928","Acme","0012345678","11111","2468","","0","1","2/11/2014 5:50:34 PM","2/10/2014"
    "100741","1004928","ABC","009999999","22222","180.34","","0","1","2/20/2014 9:01:38 PM","2/20/2014"

You can use Acct property to filter $sms_accts

... | where-object { $sms_accts.Acct -contains ($_.ACCOUNT_NUMBER.PadLeft(11,"0"))}

in this way you don't need to use foreach in your code.

You process $sms_accts into an array of custom objects with the single property Acct :

$sms_accts = $sms_accts  | Select-Object @{Name="Acct";Expression={$_.Acct.PadLeft(11,"0")}}

but then check the array for a particular string :

... | where-object { $sms_accts -contains ($_.ACCOUNT_NUMBER.PadLeft(11,"0")) }

Since none of your custom objects is a string (even though each has a string property), you don't get a match. Change the two lines

$sms_accts = import-csv -path "H:\scrap\Positive Pay Feeds\sms_accounts.txt"

and

$sms_accts = $sms_accts  | Select-Object @{Name="Acct";Expression={$_.Acct.PadLeft(11,"0")}}

into this:

$sms_accts = Import-Csv "H:\scrap\Positive Pay Feeds\sms_accounts.txt" | % {
               $_.Acct.PadLeft(11,"0")
             }

and your check will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM