string get single / multiple values - string

I have a string
<P>Microsoft Word 2003 Service Pack 3 <BR>(2863866)</P>`
from which I need to get out 3 values:
- $value1 = characters between " "
- $value2 = characters between "> </A
- $value3 = characters between ( )
Any idea how to achieve this?

Try regex:
$string = '<P>Microsoft Word 2003 Service Pack 3 <BR>(2863866)</P>`'
$regex = '"(.*?)">(.*?)<\/A>.*?\((.*?)\)'
if($string -match $regex) {
$Matches[1]
$Matches[2]
$Matches[3]
}
http://www.microsoft.com/downloads/details.aspx?FamilyId=39d8f0cd-4043-4eed-bd27-2f26748da664
Microsoft Word 2003 Service Pack 3
2863866
This would require all elements to always be there and in the same order (link, name of link, parantheses)

Related

Powershell - Reading Excel after formatting data

I have an excel file of new-hires for the company.
Firstly I need to hide all the columns that will be used for searching users.
That was pretty simple and I managed to do it. Now I'm left only with the columns I really need.
Now is the real problem:
I need to filter the data and then import those usernames to the PowerShell array.
So in excel it looks like this:
Then I have the function:
Function GetUsernames ($WorkSheet) {
$userName = $WorkSheet.UsedRange.Rows.Columns["UserNameColumn"].Value2
return $userName
}
But it's returning all of the records in the Username column - 651 records instead of 476.
The function is waiting for my input after I format the excel file manually.
Any directions will be appreciated! :)
What you seek is all the values from rows in a certain column that are not hidden in the Excel file.
To get those, you need to go through the Rows of the selected column.
In my Office version 2016, I cannot reference a column directly by its name, so I have extended your function to first find the column index.
Also, I have renamed the function a bit to follow the Verb-Noun convention in PowerShell
function Get-Usernames ($WorkSheet, $Column) {
# for me (office 2016) I cannot reference a Column by its name
# using Columns["UserNameColumn"], so I have to find the index first
$index = 0
if ($Column -is [int]) {
$index = $Column
}
else {
for ($col = 1; $col -le $WorkSheet.UsedRange.Columns.Count; $col++) {
$name = $WorkSheet.Cells.Item(1, $col).Value() # assuming the first row has the headers
if ($name -eq $Column) {
$index = $col
break
}
}
}
if ($index -gt 0) {
# now return the values in the columns for the rows that are not hidden
# skip the first row, because that is the column name itself
($WorkSheet.UsedRange.Rows.Columns($index).Rows | Select-Object -Skip 1 | Where-Object { !$_.hidden }).Value2
}
}
You can now use the function in your script like this:
$userNames = Get-Usernames $workbook.Worksheets(1) "UserNameColumn"

The number in this cell is formatted as text or preceded by an apostrophe - Powershell

I have n application made in Powershell that reads result from a database and spool the data into an Excel table. When the numbers are integer i don't have any problem, but when I'm trying to spool a decimal the next error appears: "The number in this cell is formatted as text or preceded by an apostrophe".
I've tried the next after the data insert:
$range1 = "F2:G20"
$range2 = "K2:L20"
$WorkSheet.Columns.item('F').NumberFormat = "#.##0,00"
$WorkSheet.Columns.item('G').NumberFormat = "#.##0,00"
$range = $WorkSheet.Range($range1).Copy()
$x = $WorkSheet.Range($range2).Select()
$WorkSheet.UsedRange.PasteSpecial(-4163,-4142)
But no success... There is another way? I want those 2 columns F and G to be formated as Number....
As well I've tried as well :
$WorkSheet.Columns.item('F').NumberFormat = "#.##0,00"
$WorkSheet.Columns.item('G').NumberFormat = "#.##0,00"
$Tr = $WorkSheet.Range('K2','L20')
$WorkSheet.Range('F2','G20').Copy()
$Tr.Select()
$Tr.PasteSpecial(-4163)
The values are still pasting as text and not as a decimal number...
Very important : I'm trying to paste the values in a Excel Table.
OK, after too much time i found a solution, better call it work arround:
In your Excel workbook create a table with the same name of the column of you SQL table, then insert some dummy values manually.
Get your data information from the DB in this way:
$dt1 = SQLCommand -File_Path $QueryReplacedFullPath -Server "tnsdw" -Name "TMS_SalesDW" -Out
$dt_table1 = $dt1.Tables[0]
$WorkSheet = $Workbook.worksheets | where-object {$_.Name -eq $SheetName}
$WorkSheet.Activate()
Delete the dummy data inserted manually before wit the next code:
$StartRow = 2
$FinalRow = 200
$null = $WorkSheet.Range("A$($StartRow):A$($FinalRow)")
$WorkSheet.usedrange.offset($StartRow,0).specialcells(12).Entirerow.Delete()
Insert the data in your Excel table using this command:
for ([Int]$m = 0; $m -lt $dt_table1.Rows.Count; $m++)
{
for ([Int]$r = 0; $r -lt $dt_table1.Columns.Count; $r++)
{
$incolumn = $r + 1;
$inrow = $inheaderlenght + 2 + $m;
if($incolumn -gt 4)
{
$Workbook.ActiveSheet.Cells.Item($inrow, $incolumn) = [System.Convert]::ToDecimal($dt_table1.Rows[$m].ItemArray[$r])
}
else
{
$Workbook.ActiveSheet.Cells.Item($inrow, $incolumn) = $dt_table1.Rows[$m].ItemArray[$r].ToString()
}
}
}
Note that i convert the values to decimal only in the columns that i want to be decimal.

Powershell search excel document for exact match

I am using PowerShell to search a document for a key word (TTF) and then import some data. I am searching a few thousand excel documents and about half way through it started picking up unwanted data.
The code I have is as follows
$condition1 = "TTF"
$fs1 = $ws.cells.find($condition1)
It started getting unwanted data as the excel documents started using "TTF All Day" in another cell which was at the start of the document.
How do I get powershell to only look for "TTF" exactly and not "TTF" followed by more characters.
Thanks
Try using the LookAt:=xlWhole option to specify cells containing only "TTF":
$condition1 = "TTF"
$fs1 = $ws.cells.find($condition1, LookAt:=xlWhole)
This will work
$condition1 = "TTF"
$fs1 = [void]$ws.cells.find($condition1, [Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole)
# This script illustrates how to use the Range.Find method
# with parameters to find exact match
# ------------------------------------------------------------------------------------
# Learn More:
# Range.Find Method: https://learn.microsoft.com/en-us/office/vba/api/Excel.Range.Find
# XlFindLookIn: https://learn.microsoft.com/en-us/office/vba/api/excel.xlfindlookin
# XlLookAt: https://learn.microsoft.com/en-us/office/vba/api/excel.xllookat
# Open Excel
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible=$false
$Excel.DisplayAlerts=$false
# Open Spreadsheet you want to test
$xlSource = "C:\Temp\YourSpreadsheetNameGoesHere.xlsx"
$xlBook = $Excel.Workbooks.Open($xlSource)
$xlSheet = $xlBook.worksheets.item("SheetNameGoesHere")
# What you want to seach
$searchString = "John Smith"
# Column or Range you want to seach
$searchRange = $xlSheet.Range("A1").EntireColumn
# Search
$search = $searchRange.find($searchString,
$searchRange.Cells(1,1),
[Microsoft.Office.Interop.Excel.XlFindLookIn]::xlValues,
[Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole
)
# NOT FOUND
if ($search -eq $null) {
Write-Host "Not found"
}
else { # FOUND
Write-Host "Found at row #" -NoNewline
Write-Host $search.Row
}
# Close Objects
if ($xlBook) { $xlBook.close() }
if ($Excel) { $Excel.quit() }

How to use two different outputs of one TV in MODX?

I have TV with input type "File". How can i use output of this file few times:
1. in one place as url
2. in one place as name of this file
3. in one place as size of this file
Thank you
1 - use your tv - My File
2 - use snippet like this -
[[!getNameFromPath?&path=`[[*myFileTv]]`]]
and code of this snippen is -
<?php
$path = $modx->getOption('path', $scriptProperties, '');
$fileName = basename($path);
return $fileName;
3 - use another snippet -
[[!getSizeFromPath?&path=`[[*myFileTv]]`]]
which code is -
<?php
$path = $modx->getOption('path', $scriptProperties, '');
if (!empty($path)) {
$size = filesize(MODX_BASE_PATH . ltrim($path,'/'));
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
if ($size == 0) {
return('n/a');
} else {
return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
}
}
You will have to create a snippet to output the parameter you want.. something like:
[[!outputMyFile? &attribute=name &tv=[[*myTvValue]]]]
where the snippet will do your processing on the TV value [the file name] and output the appropriate attribute you want.

How to do case-sensitive find & replace in Excel file with Powershell

I want to use Powershell to find special characters (like Greek letters) in an Excel document and replace them with HTML entities. My script looks like this:
$file = "C:\Path\To\File\test.xls"
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $True
$objWorkbook = $xl.Workbooks.Open($file)
$objWorksheet = $objWorkbook.Worksheets.Item(1)
$objRange = $objWorksheet.UsedRange
$charArray = #(
([char]948, "δ"),
([char]916, "Δ")
)
foreach ($char in $charArray){
$FindText = $char[0]
$ReplaceText = $char[1]
if ($objRange.find("$FindText")) {
$objRange.replace("$FindText", $ReplaceText)
} else {write-host "Didn't find $FindText"}
}
The trouble is, the .find() and .replace() methods are not case-sensitive, so [char]948 (δ) matches both the lowercase delta (δ) and uppercase delta (Δ) characters. The result is that all δ and Δ characters in the Excel (.xls) file are replaced with δ.
In VBA, Range.Find() has a MatchCase parameter, but it does not seem that Powershell allows it. For example, $objRange.find("$FindText", MatchCase:=$True) does not work.
I also tried Powershell's -cmatch and -creplace commands, which are case-sensitive, but I could not figure out how to get those to work on the Excel range object $objRange:
$objRange -creplace "$FindText", $ReplaceText has no effect on the Excel file.
I can't export or convert the data to .txt or .csv because the special characters don't survive the conversion.
Is there a way to make this work?
Using PowerShell you can use creplace operator
"aAaAaA" -creplace 'a','I'
IAIAIA
To replace find you can use the IndexOf method from the string class it takes a comparisonType
IndexOf(string value, int startIndex, int count, System.StringComparison comparisonType)
Example :
"Jean Paul".indexOF("paul", 0, [System.StringComparison]::CurrentCulture)
-1
"Jean Paul".indexOF("paul", 0, [System.StringComparison]::CurrentCultureIgnoreCase)
5

Resources