Store results of split function in variables - shell

I have files in a directory like below:
first-file-name
2nd-file-name
3rd-file-name
.
.
n-file-name
I need to store each portion of file name in a separate variable because I want to insert these values in separate columns of table.
For this, I used the below script to get the each portion of a file name:
$var1=$item.BaseName.Split("-",3)[0]---------first
$var2=$item.BaseName.Split("-",3)[1]---------file
$var3=$item.BaseName.Split("-",3)[2]---------name
and can save these values in a variable. But the question is how can I do this for all files, if I use foreach loop then the variable values will be overwritten???
foreach(item in $items)
{
$var1=$item.BaseName.Split("-",3)[0]---------first
$var2=$item.BaseName.Split("-",3)[1]---------file
$var3=$item.BaseName.Split("-",3)[2]---------name
}
Here, in $items I got the file path using get-childitem.

I would create a PsCustomObject with the three parts:
$parts = $items | ForEach-Object {
[PsCustomObject]#{
FirstPart = $item.BaseName.Split("-",3)[0]
SecondPart = $item.BaseName.Split("-",3)[1]
ThirdPart = $item.BaseName.Split("-",3)[2]
}
}
now $parts is an array of these objects so you can access them using e. g.
$parts[0].FirstPart

Related

Recursive deleting files from storage Laravel

I have a need to be able to delete files from storage on laravel.
My idea is to loop through the files based on the folder name (course id) using this code:
$rootPath = public_path() .'/storage/' . $course_id . '/';
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir() === FALSE){
// Get real and relative path for current file
$filePath = $file->getRealPath();
//HERE I WANT TO DELETE THE ACTUAL FILE - BUT I CAN'T GET THE FILE NAME
//$name and $file are not carrying the filenames and hence I cant delete
the file
}
}
and then I will delete each file using: Storage::delete($file);
My issue is that my iteration is not showing the filenames within the directory and I have no idea what I am doing incorrectly.
You could just iterate over the directories and use
$success = Storage::cleanDirectory($directory);
to remove all files and directories in the specified directory.

Is there a way to copy only unique rows in an Excel worksheet column to another sheet?

I use a CSV file as $AgencyMaster with two columns, AgencyID and AgencyName. I currently manually input these from another file, $Excel_File_Path, but I would like to automatically generate $AgencyMaster if possible.
$Excel_File_Path has three worksheets: Sheet1, Sheet2 and Template. Sheet1 and Sheet2 are full of data, while Template is used as a graphical representation of said data which populates based on the AgencyID. I have a script that opens $Excel_File_Path, inputs AgencyID into a specific cell, saves it, then converts it to a PDF. It does this for each AgencyID in $AgencyMaster, which is currently over 200.
In $Excel_File_Path, columns B and C in Sheet1 and Sheet2 contain all of the AgencyIDs and AgencyNames, but there are a bunch of duplicates. I can't delete any of the rows because while they are duplicates in column B and C, columns D, E, F, etc have different data used in Template. So I need to be able to take each unique AgencyID and AgencyName which may appear in Sheet1 or Sheet2 and export them to a CSV to use as $AgencyMaster.
Example:
(https://i.imgur.com/j8UIZqp.jpg)
Column B contains the AgencyID and Column C contains the AgencyName. I'd like to export unique values of each from Sheet1 and Sheet2 to CSV $AgencyMaster
I've found how to export it to a different worksheet within the same workbook, just not a separate workbook alltogether. I'd also like to save it as a .CSV with leading 0's in cell A.
# Checking that $AgencyMaster Exists, and importing the data if it does
If (Test-Path $AgencyMaster) {
$AgencyData = Import-CSV -Path $AgencyMaster
# Taking data from $AgencyMaster and assigning it to each variable
ForEach ($Agency in $AgencyData) {
$AgencyID = $Agency.AgencyID
$AgencyName = $Agency.AgencyName
# Insert agency code into cell D9 on Template worksheet
$ExcelWS.Cells.Item(9,4) = $AgencyID
$ExcelWB.Save()
# Copy-Item Properties
$Destination_File_Path = "$Xlsx_Destination\$AgencyID -
$AgencyName - $company $month $year.xlsx"
$CI_Props = #{
'Path' = $Excel_File_Path;
'Destination' = $Destination_File_Path;
'PassThru' = $true;
} # Close $CI_Props
# Copy & Rename file
Copy-Item #CI_Props
} # Close ForEach
} # Close IF
I would recommend using either Sort-Object -Unique or Group-Object.

Pick the latest file based on timestamp provided in the filename

I have to pick the files in order(first file first) from say a folder (C:\Users) and file name has the timestamp in it.
For example below are my files in C:\Users\ and the time stamp is after the first underscore i.e. 20170126102806 in the first file below. I have to loop through files and pick the first file and so on. so out of 5 files below,20170123-000011_20170126101823_AAA is the first file. How do I do this in SSIS?
1.20170123-000011_20170126102806_AAA
2.20170123-000011_20170126103251_AAA
3.20170123-000011_20170126101823_AAA
4.20170123-000011_20170126103305_AAA
5.20170123-000011_20170126102641_AAA
You can act in two ways:
use the foreach loop container to get the list of files, and then populate a database table.
Then, outside the foreach loop, use an Execute SQL to select from that table using an appropriate ORDER BY. Load an object variable with the result set. Then use a second foreach loop to step through the variable object and collect files.
use a Script Task to retrieve the contents of the folder (the list of files) and sort files then load an object variable with the dataset. Then use a foreach loop to step through the variable object to collect files.
I hope this help.
You could use a script task in a For Each Loop. Use the filename returned as the source to load each time.
using System.IO;
public void Main()
{
string filePath = "D:\\Temp";
DirectoryInfo dir = new DirectoryInfo(filePath);
var files = dir.GetFiles("*_AAA");//Or from a variable
DateTime fileCreateDate1 = File.GetCreationTime(filePath + "\\" + files[0]);
if (files.Length >= 2)
{
for (int i = 1; i < files.Length; i++)
{
DateTime fileCreateDate2 = File.GetCreationTime(filePath+ "\\" + files[i]);
if (fileCreateDate1 < fileCreateDate2)
{
fileCreateDate1 = fileCreateDate2;
}
}
}
Dts.Variables["User::FileToLoad"].Value = fileCreateDate1;
Dts.TaskResult = (int)ScriptResults.Success;
}
You will have to remove the file after it was loaded or else it will be loaded each time as it is the oldest or latest file.
There might be a bug or so, but have similar code that works. Just iron it out if needed.

_REQUEST only returning the first letter of input

I am trying to update records in a database through a form (post), but when I access the global parameter variables, only the first character of the original input is returned for some reason.
$conn->beginTransaction();
$sql = "UPDATE AS_PEOPLE SET pid=? WHERE name=?";
$stmt = $conn->prepare($sql);
$values = Array($_REQUEST['project'][0], $_REQUEST['person'][0]);
$stmt->execute($values);
$conn->commit();
echo "Ressource allocated<br>";
print_r($values);
Your problem is here
$values = Array($_REQUEST['project'][0], $_REQUEST['person'][0]);
$_REQUEST['project'] and $_REQUEST['person'] are strings, containing values of selected option. If you tell php to get the index of 0 of a string it returns the first letter only
$values = Array($_REQUEST['project'], $_REQUEST['person']);

Vtiger select query

I'm copying a vtiger query in a similar way but there is one change that the query given first having only one output so there is kept 0 in 2nd argument,
but in my customized query there are multiple outputs so what should I kept instead of 0
both are given as below:
original query
$is_recurring_event_query = $adb->pquery('SELECT recurring_group_id from vtiger_activity where activityid=?',array($id));
$is_recurring_event = $adb->query_result($is_recurring_event_query,0,'recurring_group_id');
copying it to use at different way
$is_recurring_event_activity_query = $adb->pquery('SELECT activityid from vtiger_activity where recurring_group_id='.$is_recurring_event);
$is_recurring_event_activity = $adb->query_result ($is_recurring_event_activity_query,0,'activityid');
You have to put variable and have to use for loop for your query to execute and get multiple values.
Suppose your query is like this
$result = $adb->pquery ('SELECT * from vtiger_activity where id='.$recordId);
$noofrow = $adb->num_rows($result );
for($i=0; $i<$noofrow ; $i++) {
$Data['activityid']=$adb->query_result($result,$i,'activityid');
$Data['activityname']=$adb->query_result($result,$i,'activityname');
}
Here in $Data you will get an array of the values.

Resources