Powershell excel replace always returns true - powershell

I've doing a find and replace in a whole bunch of excel files (to update some links that have moved)
I want to track which files had changes made to them however the result of a replace is always true regardless of if the required text was is there. A find like this:
$worksheet.UsedRange.Find($Text)
will either return null if the text being looked for does not exist or an object if it does, but thats significant extra processing I'd prefer to remove given that I have about 1.2million files to check.
Here is my replace code:
$found=$false
$xlCalculationManual = -4135
$excel = New-Object -comobject Excel.Application
$excel.visible = $false
$excel.AskToUpdateLinks = $false
$excel.DisplayAlerts = $false
$excel.EnableEvents = $false
$workbook=$excel.Workbooks.Open($openfile,0,$false,5,"nopassword","nopassowrd")
$excel.Calculation = $xlCalculationManual
foreach ($worksheet in $workbook.Sheets)
{
foreach ($Text in $FindText)
{
If ($worksheet.UsedRange.replace($Text,$ReplaceText))
{
$found=$true
}
}
}

Looks like Theo is correct on this. I've not found anyway to increase the efficiency by removing the find.
Also it seems that on some files a replace only replaces the first instance and therefore a loop is also required.

Maybe try
$worksheet.UsedRange.replace($Text,$ReplaceText)
If ($?)
Instead of
If ($worksheet.UsedRange.replace($Text,$ReplaceText))
OR you could try searching for the text, and confirm that it found something?
Before your if replace option, try (I apologize, but this code is speculation, and may not full fix it. There is an article on this at https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel
$confirm = $worksheet.Used.Range.find($text)
if ($confirm -ne $null) {
Echo $true
$worksheet.UsedRange.replace($Text,$ReplaceText)
$confirm = $null
}
else{
echo $false
}

Related

creating a System.Windows.Forms.Textbox that would accept array input

i'm looking for help in creating a System.Windows.Forms.Textbox that would accept array input and treat it as an array input, rn textbox properties looks something like this:
$boxname.AcceptsReturn = $true
$boxname.MultiLine = $true
$boxname.Autosize = $true
$boxname.AcceptsTab = $false
$boxname.Scrollbars = 'Vertical'
If i enter multiline paths like this:
C:\Windows
C:\Program Files
C:\Temp
$boxname.text is treated like one huge string and won't let my "test-path on each item in array" function work properly, i bound it to this box with .Add_TextChanged, what i'm trying to do is to create a box, that will perform a check that entered paths exist once the box is filled.
Is this even possible without additional parsing ? Maybe i'm missing something.
You need to split the multiline text into separate lines and then loop over these lines to do your checks.
$boxname.Add_TextChanged({
# inside the eventhandler, you can refer to the control object itself using automatic variable $this
$this.Text -split '\r?\n' -ne '' | ForEach-Object {
if (-not(Test-Path -Path $_)) {
# path does not exist, do something..
Write-Host "Path '$_' not found!"
}
}
})

Embed a text file as an object in Ms Word 2010

I am building a script to write word documents using PowerShell (Windows 7, PS4, .Net 4, Office 2010.
The script works but it embeds the text at the top of the document. I need to be able to specify the exact location like on page 2.
Here's what I got up to date:
# Opens an MsWord Doc, does a Search-and-Replace and embeds a text file as an object
# To make this work you need in the same folder as this script:
# -A 2-page MsWord file called "Search_and_replace_Target_Template.doc" with:
# -the string <package-name> on page ONE
# -the string <TextFile-Placeholder> on page TWO
# -A textfile called "TextFile.txt"
#
#The script will:
# -replace <package-name> with something on page one
# -embed the text file <package-name> at the top of page one (but I want it to replace <TextFile-Placeholder> on page 2)
#
# CAVEAT: Using MsWord 2010
[String]$MsWordDocTemplateName = "Search_and_replace_Target_Template.doc"
[String]$TextFileName = "TextFile.txt"
[Int]$wdReplaceAll = 2
[Int]$wdFindContinue = 1 #The find operation continues when the beginning or end of the search range is reached.
[Bool]$MatchCase = $False
[Bool]$MatchWholeWord = $true
[Bool]$MatchWildcards = $False
[Bool]$MatchSoundsLike = $False
[Bool]$MatchAllWordForms = $False
[Bool]$Forward = $True
[Int]$Wrap = $wdFindContinue #The find operation continues when the beginning or end of the search range is reached.
[Bool]$Format = $False
[Int]$wdReplaceNone = 0
$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $true #Makes the MsWord
[String]$ScriptDirectory = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.path)
[String]$WordDocTemplatePath = "$ScriptDirectory\$MsWordDocTemplateName"
[String]$TextFilePath = "$ScriptDirectory\$TextFileName"
[String]$SaveAsPathNew = Join-Path -Path $ScriptDirectory -ChildPath "${MsWordDocTemplateName}-NEW.doc"
#Open Template with MSWord
Try {
$objDoc = $objWord.Documents.Open($WordDocTemplatePath)
} Catch {
[string]$mainErrorMessage = "$($_.Exception.Message) $($_.ScriptStackTrace) $($_.Exception.InnerException)"
Write-Host $mainErrorMessage -ForegroundColor Red
Start-Sleep -Seconds 7
$objDoc.Close()
$objWord.Quit()
}
$objSelection = $objWord.Selection
$objSelection.Find.Forward = 'TRUE'
$objSelection.Find.MatchWholeWord = 'TRUE'
#Replace <package-name>
[String]$FindText = "<package-name>"
[String]$ReplaceWith = "PackageName_v1"
write-host "replacing [$FindText] :" -NoNewline
$objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
#Embed the text file as an object
[System.IO.FileSystemInfo]$TextFileObj = Get-item $TextFilePath
If ( $(Try {Test-Path $($TextFileObj.FullName).trim() } Catch { $false }) ) {
write-host "Embedding [$TextFileName] :" -NoNewline
[String]$FindText = "<TextFile-Placeholder>"
[String]$ReplaceWith = ""
# $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
#Need code to create a RANGE to the position of <TextFile-Placeholder>
#Embed file into word doc as an object
#$result = $objSelection.InlineShapes.AddOLEObject($null,$TextFileObj.FullName,$false,$true)
$result = $objSelection.Range[0].InlineShapes.AddOLEObject($null,$TextFileObj.FullName,$false,$true) #works too but does the same
Write-host "Success"
} Else {
Write-Host "[$TextFilePath] does not exist!" -ForegroundColor Red
Start-Sleep -Seconds 5
}
Write-Host "Saving updated word doc to [${MsWordDocTemplateName}-NEW.doc] ***"
Start-Sleep -Seconds 2
#List of formats
$AllSaveFormat = [Enum]::GetNames([microsoft.office.interop.word.WdSaveFormat])
$SaveFormat = $AllSaveFormat
$objDoc.SaveAs([ref]$SaveAsPathNew,[ref]$SaveFormat::wdFormatDocument) #Overwrite if exists
$objDoc.Close()
$objWord.Quit()
$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$objWord)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable objWord
If you have a way to do this in Word 2016 I'll take it too as I'll have to redo it all for office 2016 later on.
UPDATE: Looks like the solution is to create a "Range" where the is located. By default it seems you have one range[0] that represents the whole document.
The closest I came to do this was:
$MyRange = $objSelection.Range[Start:= 0, End:= 7]
But this is not the syntax for PowerShell and it deals only with absolute character positions and not the results of a search for a string.
If I could create a 2nd range maybe this could work:
$objSelection.Range[1].InlineShapes.AddOLEObject($null,$TextFileObj.FullName,$false,$true)
I can't write powershell script for you, but I can describe what you need. You are, indeed, on-track with the Range idea. To get the Range for an entire Word document:
$MyRange = $objDoc.Content
Note that you're free to declare and use as many Range objects as you need. Range is not limited like Selection, of which there can be only one. As long as you don't need the original Range again, go ahead and perform Find on it. If you do need the original Range again, then declare and instantiate a second, instantiating it either as above or, in order to use the original as the starting point:
$MyRange2 = $MyRange.Duplicate
Then use Find on a Range. Note that, when Find is successful the content of the Range is the found term, which puts the "focus" on the correct page. (But will not move the Selection!)
$MyRange.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceAll)
If you want to test whether Find was successful the Execute method returns a Boolean value (true if Find was successful).
Use something like what follows to insert the file, although I'm not sure OLEObject is the best method for inserting a text file. I'd rather think InsertFile would be more appropriate. An OLEObject requires an OLE Server registered in Windows that supports editing text files; it will be slower and put a field code in the document that will try to update...
$result =$MyRange.InlineShapes.AddOLEObject($null,$TextFileObj.FullName,$false,$true)

Disable $OKButton until textbox is populated?

I have a question on an event trigger. I'd like to have my OKButton be disabled until a textbox(s) are populated, pretty much requiring the user to input data into that field or cancel out of the form. I have $OKButton.enabled = $false already and think I need something along the lines of
if ($Textbox3.Text.Length <1) {
$OKButton.enabled = $true
} else {
$OKButton.enabled = $false
}
I have this piece of code in my script currently and the OK button is disabled but I think I am having a syntax error because when Textbox3 is filled the button remains disabled.
In PowerShell, the "less-than" comparison operator is not < but rather -lt (short for, you guessed it, less than):
if ($Textbox3.Text.Length -lt 1) {
$OKButton.enabled = $true
} else {
$OKButton.enabled = $false
}
Read more about comparison operators in PowerShell with Get-Help about_Comparison_Operators

Powershell CheckedListBox check if in string / array

I've started learning Powershell and am now stuck after spending several hours on a problem I can find solutions for in multiple languages except Powershell.
I need to place a check against each item in a CheckedListBox that matches any of the values in a semi-colon delimited string named $MLBSVar_SelectedPackages. (eg. $MLBSVar_SelectedPackages = 'packageA;packageB;packageC;') and so on.
I've come up with this line but it doesn't yet work. Please can you help me?
if ($MLBSVar_SelectedPackages -ne $null) {
ForEach ($PackageName in $MLBSVar_SelectedPackages) {
ForEach ($item in $clb_SC_AvailablePackages.Items) {
if ($item -eq $PackageName) {
$clb_SC_AvailablePackages.Item($PackageName).Checked = $true
}
}
}
}
I've also tried .SetItemCheckState([System.Windows.Forms.CheckState]::Checked) in place of .Checked. The (one) issue seems to be getting a handle on the list item in the final section as it seems to be passed as a string rather than object? I have a VBS background and would really appreciate the assistance.
I think what you're looking for is something like the following code. You can use the SetItemChecked() method of the CheckedListBox class to check an item at a particular index. I see that you have attempted to use SetItemCheckState(), but did not make mention of SetItemChecked().
# Import Windows Forms Assembly
Add-Type -AssemblyName System.Windows.Forms;
# Create a Form
$Form = New-Object -TypeName System.Windows.Forms.Form;
# Create a CheckedListBox
$CheckedListBox = New-Object -TypeName System.Windows.Forms.CheckedListBox;
# Add the CheckedListBox to the Form
$Form.Controls.Add($CheckedListBox);
# Widen the CheckedListBox
$CheckedListBox.Width = 350;
$CheckedListBox.Height = 200;
# Add 10 items to the CheckedListBox
$CheckedListBox.Items.AddRange(1..10);
# Clear all existing selections
$CheckedListBox.ClearSelected();
# Define a list of items we want to be checked
$MyArray = 1,2,5,8,9;
# For each item that we want to be checked ...
foreach ($Item in $MyArray) {
# Check it ...
$CheckedListBox.SetItemChecked($CheckedListBox.Items.IndexOf($Item), $true);
}
# Show the form
$Form.ShowDialog();
After running this code, you should be presented with a dialog that looks similar to the following screenshot.

Table Cycling for Powershell

I'm creating a powershell script that I want to read a value (VALUE1) from an excel table (I can convert it to XML if necessary), assign it to a variable($PLACEHOLDER), run the rest of the script, then loop back to the beginning, but instead of reading the original value(VALUE1) I want it to read the value below it(VALUE2) and overwrite $PLACEHOLDER with VALUE2, then re-run the script until it returns a blank value, then I want it to stop. I am insanely new to powershell and it's interaction with excel/xml, so any help would be greatly appreciated. (I'm self-taught, so I don't know TOO much about parameters)
Sample in Terrible Psuedo:
#Initial placeholder value here
$RowNumber = 0
#Start of the loop here, add one to previous value
$RowNumber +1
#Call the value in Column (1), Row ($RowNumber), and assign it to $RowValue
?????? = $RowValue
#Execute the command involving the data value
ECHO "C:/test/temporary/$RowValue"
#Goto the start of the loop.
If you could be so kind, would you please give a quick explanation of the functions that you use (Parameters, what's happening, ect.)
EDIT: If it could detect and skip over blank rows, that would be amazing.
EDIT3: Code for Ansgar
$xl = New-Object -COM 'Excel.Application'
$xl.Visible = $true # set to $false for production
$wb = $xl.Workbooks.Open("C:\Documents and Settings\xe474109\Desktop\EXCEL FILES\testbook2.xlsx")
$ws = $wb.Sheets.Item(1)
$row = $ws.UsedRange.Rows.Count
while ( $ws.Cells.Item($row, 1).Value -ne $null ) {
$PLACEHOLDER = $ws.Cells.Item($row, 1).Value
#
# do stuff with $PLACEHOLDER here
#(I wanted to test this by just printing the $PLACEHOLDER value
$PLACEHOLDER
$row++
}
$wb.Close()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
Do you have Excel installed? If so, you can process Excel spreadsheets like this:
$xl = New-Object -COM 'Excel.Application'
$xl.Visible = $true # set to $false for production
$wb = $xl.Workbooks.Open('C:\path\to\your.xlsx')
$ws = $wb.Sheets.Item(1)
$row = $ws.UsedRange.Row
while ( $ws.Cells.Item($row, 1).Value -ne $null ) {
$PLACEHOLDER = $ws.Cells.Item($row, 1).Value
#
# do stuff with $PLACEHOLDER here
#
$row++
}
$wb.Close()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
cls
$csv = Import-csv -Path 'C:\test\csvStuff.csv'
foreach ($rec in $csv) {
if ($rec.nameofyourcolumn -ne '') {
& "c:\test\temporary\$($rec.nameofyourcolumn)"
}
}