Manipulate text file - change multiple lines - powershell

Have been looking at what I thought would be a really simple task this morning.... and turns out it wasn't, at least not for me.
What I am trying to do is get powershell to read through an ini-file, and change multiple values under specific headers only.
[Datoformat]
Separator=.
[Database]
Path=servername:d:\mycompany\nextsys_db\next.fdb
DokumentDbPath=
FireBird25=Nei
[Pictures]
Path=T:\nextsys_bilde
DbExtractFolder=
[Brukerinnstillinger]
Prioriter=Ja
�pneJournalAuto=Nei
TillatBrukerBytte=Ja
EnkelJournal=Nei
AvtBokRadHoyde=
AvtBokMndKolonneBredde=
Resepsjonsmaskin=Nei
Tilgangsoversikt=Nei
AvtaleHentPasientAutomatisk=Ja
VisFargeForAnsvarlig=Nei
[Eksport]
Automatisk=Nei
[Import]
Automatisk=Nei
[Skjerm]
HuskSkjermPosisjon=Ja
ProgramSkjermPosX=-8
ProgramSkjermPosY=-8
ProgramSkjermBredde=1936
ProgramSkjermHoyde=1056
MaksimertSkjermPosisjon=Ja
EgenDefSkjermSizeX=1919
EgenDefSkjermSizeY=1080
UtvidetAvtalebok=Ja
UtvidetJournal=Ja
UtvidetRecall=Ja
UtvidetOmsetning=Ja
UtvidetUtestaaende=Ja
UtvidetRegnskap=Ja
UtvidetFakturaOversikt=Ja
UtvidetGenerelleModuler=Ja
UtvidetAlleModuler=Ja
1280800=Nei
1440900=Nei
16801050=Nei
19201080=Nei
Egendefinert=Ja
AutomaticSize=Nei
[Spesialinnstillinger]
EnForekomst=Nei
TestModusInfo=Nei
AktiverRegningskortJournalSjekk=Nei
IkkeSpmOmHelseskjema=Nei
IkkeSpmOmBrukerBytteAvtale=Nei
IkkeSpmOmBrukerBytteAnsvarlig=Nei
[Vedlegg]
Path=
[Avtalebok]
Utseende=
Bakgrunn=
[Journal]
JournalTextSize=8
JournalTextFont=
JournalTextStyle=
FetSkrift=Nei
[Rontgen]
AlternativAapning=Nei
[Utseende]
IkkeVisDagensPasienter=Nei
[MediLink]
BenyttMediLink=Nei
AutomatiskInnlesing=Nei
MediLinkInnlesingIntervall=
[AutomatiskOppdatering]
VedOppstart=Nei
Alltid=Nei
FraLokaltNettverk=Nei
NettverkPath=
UtenBekreftelse=Nei
[BankTerminal]
PosPay=Nei
BetTermAlwaysOn=Ja
BBSFlerBrukerTerminal=Nei
ThisMerchantHighest=Nei
MerchantId=
TerminalId=
BrukerBoPosDrivere=Nei
BrukerBaxiDrivere=Ja
BaxiAktiverXReport=Ja
BaxiAktiverZReport=Nei
BaxiAktiverReversal=Nei
[EasyPanel]
Benytt=Nei
Notat=Nei
Diagnose=Nei
Epikriser=Nei
Sykemelding=Nei
Resept=Nei
Henvisning=Nei
Helseskjema=Nei
Endo=Nei
Perio=Nei
Bilder=Nei
Tekn.skjema=Nei
Skjema=Nei
Dokumentmodul=Nei
[Oppstartsbilde]
VisesVedOppstart=Nei
[Printer]
LokaltOppsett=Ja
TryktA5Resept=Nei
TryktA5ReseptDesign2=Nei
TimeKortKvittSkriver=Nei
VisMinimalBaxInfo=Nei
ReseptKvittSkriver=Nei
JusteringVenstreMargX=
JusteringToppMargY=
Faktura=HP LaserJet Pro MFP M125-M126 PCLmS
Recallkort=HP LaserJet Pro MFP M125-M126 PCLmS
Timekort=HP LaserJet Pro MFP M125-M126 PCLmS
Kvittering=HP LaserJet Pro MFP M125-M126 PCLmS
Resept=HP LaserJet Pro MFP M125-M126 PCLmS
Standard=HP LaserJet Pro MFP M125-M126 PCLmS
Tekniker=HP LaserJet Pro MFP M125-M126 PCLmS
FakturaStorrelse=A4
RecallKortStorrelse=A4
TimekortStorrelse=A4
KvitteringStorrelse=A4
ReseptStorrelse=A4
TeknikerStorrelse=A4
StandardStorrelse=A4
FakturaOppsettKode=
RecallkortOppsettKode=
TimekortOppsettKode=
KvitteringOppsettKode=
ReseptOppsettKode=
TeknikerOppsettKode=
StandardOppsettKode=
FakturaPapirretning=St�ende
RecallKortPapirretning=St�ende
TimekortPapirretning=St�ende
KvitteringPapirretning=St�ende
ReseptPapirretning=St�ende
TeknikerPapirretning=St�ende
StandardPapirretning=St�ende
FakturaPreview=Ja
RecallKortPreview=Ja
TimekortPreview=Ja
KvitteringPreview=Ja
ReseptPreview=Ja
TeknikerPreview=Ja
StandardPreview=Ja
[Paaminnelse]
Automatisk=Nei
AutomatiskService=Nei
Tidspunkt=
Dagens=Nei
KunMerketOnsker=Nei
AutomatiskEpost=Nei
AntallDagerFrem=Nei
AntallDagerFremAntall=2
ErstattTekst=Nei
PaaminnelseTekst=Hei [fornavn], minner om time reservert til deg: [dato] kl. [tid]. Timer som ikke passer m� avbestilles senest 24 timer i forveien. Mvh. [tittel] [brukernavn]
[SMS]
Testmodus=Nei
VisAdvarslerVedIkkeSendtSMS=Nei
[Innlogging]
TillatInnloggingMedEldreProgramversjonEnnDatabase=Nei
I want to change the values "Automatisk=Nei" to "Automatisk=Ja", "Tidspunkt=" to "Tidspunkt=10:00" and "AntallDagerFrem=Nei" to "AntallDagerFrem=Ja"... The Tidspunkt and AntallDagerFrem values shouldn't be that hard since they only appear once in the file, but "Automatisk=Nei" appears 4 times, and I only want to change the one below [Paaminnelse]
$content = #(if ((Get-Content $inifile) -join "`n" -match '\[Paaminnelse\]([\s\S]*)\[SMS\]') { $Matches[1] })
$newcontent = $test -replace 'Automatisk=Nei','Automatisk=Ja' -replace 'Tidspunkt=','Tidspunkt=10:00' -replace 'AntallDagerFrem=Nei','AntallDagerFrem=Ja'
This finds the correct lines from the ini-file and changes the values I want to change, but using Set-Content $inifile -Value $newcontent will of course remove all everything else from the file which is not what I want :)
More used to cat, grep, awk and sed than PowerShell to be honest so any pointers would be helpful.

As Theo notes, consider using a dedicated INI file parser, such as the one provided by the third-party PsIni module - see this answer for how to install and use it.
Update: Your own answer now shows how to use it to solve your specific problem.
If installing a module isn't an option, I suggest using a -switch statement, which has awk-like capabilities:
# Array of sample lines, as would be returned by:
# Get-Content $inifile
$iniFileLines = #'
[Datoformat]
Separator=.
[Eksport]
Automatisk=Nei
[Paaminnelse]
Automatisk=Nei
AutomatiskService=Nei
Tidspunkt=
[Printer]
AutomatiskEpost=Nei
AntallDagerFrem=Nei
AntallDagerFremAntall=2
'# -split '\r?\n'
$inPaaminnelseSect = $false
# Note: To operate directly on your file, replace
# ($iniFileLines) with -File $iniFile
switch -Regex ($iniFileLines) {
'^(Tidspunkt)=$' { '{0}=10:00' -f $Matches[1]; continue }
'^(AntallDagerFrem)=Nei' { '{0}=Ja' -f $Matches[1]; continue }
'^(Automatisk)=Nei' {
if ($inPaaminnelseSect) { '{0}=Ja' -f $Matches[1] } else { $_ }; continue
}
'^\[(.+)\]' { $inPaaminnelseSect = $Matches[1] -eq 'Paaminnelse'; $_ }
default { $_ } # pass through
}
Note:
The above assumes:
that your file has exactly the format as shown in your question. However, it would be easy to make parsing more flexible with respect to optional whitespace.
that you only want to replace entries if they have a specific current value (or none); this too could easily be changed to replace the values irrespective of the current value.
Matching is case-insensitive, as PowerShell generally is by default; add the -CaseSensitive switch to make it case-sensitive.
Output:
[Datoformat]
Separator=.
[Eksport]
Automatisk=Nei
[Paaminnelse]
Automatisk=Ja
AutomatiskService=Nei
Tidspunkt=10:00
[Printer]
AutomatiskEpost=Nei
AntallDagerFrem=Ja
AntallDagerFremAntall=2

Theo and mklement0 have both pointed to the PsIni-module which does exactly what I wanted to do - so consider the question answered.
Set-IniContent $inifile -Sections 'Paaminnelse' -NameValuePairs #{
Automatisk='Ja'; Tidspunkt='10:00'; AntallDagerFrem='Ja'
} | Out-IniFile $inifile -Force

Related

Powershell: Passed array returns $true [duplicate]

This question already has answers here:
How do I pass multiple parameters into a function in PowerShell?
(15 answers)
Closed last year.
I'm pretty sure I have some synthax error in here, but i can't find it.
I wrote this little script here to find some Files in a Folder - I want all the Filepaths that don't have some of the terms in the $excludeList in there but my Contains-Function always returns $true. And when I enable the Write-Output-Line, it also, always sais $true
$path = 'C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications'
$excludeList = #('Test', 'Samples', 'BaseApp\Source', 'Application\Source', 'system application\source')
function Contains([string]$Fullpath, $ExcludeList) {
$result = $false
#Write-Output $ExcludeList
$ExcludeList | % { $result = ($FullPath.Contains($_) -or $result) }
return $result
}
(Get-ChildItem $path -Filter '*.app' -Recurse).FullName | % {
if (!(Contains($_, $excludeList))) { $_ }
}
Here is the List of Files I'm trying to filter:
C:\WINDOWS\system32> (Get-ChildItem $path -Filter '*.app' -Recurse).FullName
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\AMCBanking365Fundamentals\Source\Microsoft_AMC Banking 365 Fundamentals.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\AMCBanking365Fundamentals\Test\Microsoft_AMC Banking 365 Fundamentals Test Automations.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\APIV1\Source\Microsoft__Exclude_APIV1_.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\APIV1\Test\Microsoft__Exclude_APIV1_ Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\APIV2\Source\Microsoft__Exclude_APIV2_.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\APIV2\Test\Microsoft__Exclude_APIV2_ Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Application\Source\Microsoft_Application.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Base Application.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Czech language (Czechia).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Danish language (Denmark).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Dutch language (Belgium).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Dutch language (Netherlands).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_English language (Australia).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_English language (Canada).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_English language (New Zealand).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_English language (United Kingdom).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_English language (United States).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Finnish language (Finland).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_French language (Belgium).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_French language (Canada).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_French language (France).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_French language (Switzerland).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_German language (Austria).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_German language (Germany).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_German language (Switzerland).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Icelandic language (Iceland).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Italian language (Italy).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Italian language (Switzerland).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Norwegian language (Norway).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Russian language (Russia).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Spanish language (Mexico).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Spanish language (Spain).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Source\Microsoft_Swedish language (Sweden).app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Library-NoTransactions.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Bank.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Cash Flow.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Cost Accounting.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-CRM integration.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Data Exchange.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Dimension.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-ERM.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Fixed Asset.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-General Journal.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Graph.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Integration.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Invoicing.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Job.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Local.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Marketing.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Misc.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Monitor Sensitive Fields.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Permissions.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Physical Inventory.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Prepayment.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Rapid Start.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Report.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Resource.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Reverse.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-SCM.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-SINGLESERVER.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-SMB.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-SMTP.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-TestLibraries.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Upgrade.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-User.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-VAT.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\BaseApp\Test\Microsoft_Tests-Workflow.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\ClientAddIns\Source\Microsoft__Exclude_ClientAddIns_.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\CompanyHub\Source\Microsoft_Company Hub.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\CompanyHub\Test\Microsoft_Company Hub Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\DataArchive\app\Microsoft_Data Archive.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\DataArchive\test\Microsoft_Data Archive Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\datacorrectionfa\source\Microsoft_Troubleshoot FA Ledger Entries.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - Current User Connector\Source\Microsoft_Email - Current User Connector.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - Current User Connector\Test\Microsoft_Email - Current User Connector Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - Microsoft 365 Connector\Source\Microsoft_Email - Microsoft 365 Connector.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - Microsoft 365 Connector\Test\Microsoft_Email - Microsoft 365 Connector Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - Outlook REST API\Source\Microsoft_Email - Outlook REST API.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - Outlook REST API\Test\Microsoft_Library Outlook REST API.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - SMTP Connector\Source\Microsoft_Email - SMTP Connector.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Email - SMTP Connector\Test\Microsoft_Email - SMTP Connector Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\EssentialBusinessHeadlines\Source\Microsoft_Essential Business Headlines.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\EssentialBusinessHeadlines\Test\Microsoft_Essential Business Headlines Test.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\LatePaymentPredictor\Source\Microsoft_Late Payment Prediction.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\LatePaymentPredictor\Test\Microsoft_Late Payment Prediction Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\microsoftuniversalprint\source\Microsoft_Universal Print Integration.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\onprem permissions\source\Microsoft_OnPrem Permissions.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\onprem permissions\test\Microsoft_OnPrem Permissions Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\Onprem Permissions DACH\Source\Microsoft_OnPrem Permissions DACH.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\paypalpaymentsstandard\source\Microsoft_PayPal Payments Standard.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\paypalpaymentsstandard\test\Microsoft_PayPal Payments Standard Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\recommendedapps\source\Microsoft_Recommended Apps.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\recommendedapps\test\Microsoft_Recommended Apps Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\salesandinventoryforecast\source\Microsoft_Sales and Inventory Forecast.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\salesandinventoryforecast\test\Microsoft_Sales and Inventory Forecast Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\sendtoemailprinter\source\Microsoft_Send To Email Printer.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\simplifiedbankstatementimport\source\Microsoft_Simplified Bank Statement Import.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\SwissQRBill\Source\Microsoft_QR-Bill Management for Switzerland.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\SwissQRBill\Test\Microsoft_QR-Bill Management for Switzerland Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\system application\source\Microsoft_System Application.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\system application\test\Microsoft_System Application Test Library.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\system application\test\Microsoft_System Application Test.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\performancetoolkit\Microsoft_Performance Toolkit Samples.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\performancetoolkit\Microsoft_Performance Toolkit Tests.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\performancetoolkit\Microsoft_Performance Toolkit.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\TestLibraries\Any\Microsoft_Any.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\TestLibraries\Assert\Microsoft_Library Assert.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\TestLibraries\permissions mock\Microsoft_Permissions Mock.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\TestLibraries\Variable Storage\Microsoft_Library Variable Storage.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\testframework\TestRunner\Microsoft_Test Runner.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\vatgroupmanagement\source\Microsoft_VAT Group Management.app
C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications\vatgroupmanagement\test\Microsoft_VAT Group Management Tests.app
Please tell me what went wrong, and if you know a way to achieve the same result more smoothly, I'm open for suggestions :)
Thank you in advance.
you need to remove parenthesis and comma in - if (!(Contains($_, $excludeList))) { $_ }
you have a problem with passing argument to a function.
look here: How do I pass multiple parameters into a function in PowerShell?
$path = 'C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications'
$excludeList = #('Test', 'Samples', 'BaseApp\Source', 'Application\Source', 'system application\source')
function Contains([string]$Fullpath, $ExcludeList) {
$result = $false
#Write-Output $ExcludeList
$ExcludeList | % { $result = ($FullPath.Contains($_) -or $result) }
return $result
}
(Get-ChildItem $path -Filter '*.app' -Recurse).FullName | % {
if (!(Contains $_ $excludeList)) { $_ }
}
$path = 'C:\bcartifacts.cache\onprem\19.2.32968.33504\ch\Applications'
[string[]]$excludeList = #('Test', 'Samples', 'BaseApp\\Source', 'Application\\Source', 'system application\\source')
[string]$excludeListRegex = $excludeList -join('|')
(Get-ChildItem $path -Filter '*.app' -Recurse).FullName | % {
if ($_ -notmatch $excludeListRegex) { $_ }
}
This is a trick I've used in the past. Basically you are dynamically creating one big regex query and using that to match the lines. Downside is you must format the entries in the ExcludeList array in a regex friendly manner. You'll notice I escaped all the backslashes with backslashes. Backslash IS the escape char in regex so if you just want an actual backslash you have to type two backslahes like I did. The upside is this is really fast because the alternative is nested loops where you'd have to iterate through every file in the list once for every exclusion. Another downside is that i'm sure there's a limit to how long that regex query can get (not sure offhand what it is) but it's not infinitely scalable.
I believe there may be a more elegant way to code this but I'd have to put a lot more thought into it. ;-)

Powershell query multidimensional hash

I'm struggling creating and querying data of an object. (I think hash table)
two environment (test and production)
two servertypes per environment (webserver and appl servers)
1 or more servers of each type
I want to store the hostnames within the applicable section. I created the following hash:
$arr =#{}
$arr.Environment = #{}
$arr.Environment.Production = #{}
$arr.Environment.Production.serverType = #{}
$arr.Environment.Production.serverType.webServer = #{}
$arr.Environment.Production.serverType.entServer = #{}
$arr.Environment.Test = #{}
$arr.Environment.Test.serverType = #{}
$arr.Environment.Test.serverType.webServer = #{}
$arr.Environment.Test.serverType.entServer = #{}
I found that I can access data like:
$serversArray.Environment.Test.serverType.webServer
I would like to know:
is this the right way of doing this? are there better / easier way to accomplish this?
how do I loop/filter this object, retrieving servernames that meet the specified criteria? Since I need to have 1. all test webservers then 2. all test appl servers etc
thanks
If you're able to save all this in one go (using variables or hardcoded strings), you should be using the native format to store it - much more readable.
See
$Optiplex = #{
'Brand' = 'Dell'
'Model' = 'Optiplex'
'Specs' = #{
'RAM' = '4 GB'
'CPU' = 'Intel i5'
'USB Ports' = '3'
'CD/DVD Drive' = 'No'
'HDD' = '320 GB - SSD'
} #Specs
} #Optiplex
From this walkthrough
You'll be able to access the variables for the hashtable in the same way, such as Optiplex.Specs.RAM to get the value for RAM.
Edit: To better answer question number 2, here's some idea on looping:
foreach ($serverTypeToKVs in $arr.Environment.Production.serverType.GetEnumerator()) {
Write-Host "ServerType $(serverTypeToKVs.Name):"
foreach ($keyVal in $serverTypeToKVs.Value.GetEnumerator()) {
# Logic if serverTypeToKVs.Name == "webServer"
# Logic if keyVal == something
# General work to be done
}
}
I found following way to achieve this:
$order = #(("Test","Production"),("webServer", "entServer"))
foreach($env in $order[0]) {
Write-Host "Environment: $env"
foreach($svr in $order[1]) {
Write-Host "ServerType: $svr"
write-host "hostnames: "$serversArray.Environment.$($env).serverType.$($svr)
}
}
This will loop the correct way/sequence and lists correct servers:
Environment: Test
ServerType: webServer
hostnames: tweb1 tweb2
ServerType: appServer
hostnames: tapp1
Environment: Production
ServerType: webServer
hostnames: pweb1 pweb2 pweb3
ServerType: appServer
hostnames: papp1 papp2 papp3 papp4

Powershell -trying to fetch the description field of bulk users

$s=[ADSI]"LDAP://CN=PF Migrated - Inbox804923#aecom.com,OU=ContactObjects,OU=Exchange,DC=na,DC=aecomnet,DC=com"
$s.description
Folder path: \ANZ\Townsville\Projects\606x\60608278_NW Traffic & Safety Plan\Inbox
In the above scenario $s.description gives me the description but in below loop $contact gives correct info but $contact.description shows nothing
foreach($u in $pf)
{
$contact= -join ('[ADSI]"LDAP://' + "$($u.Distinguishedname)" + '"')
$contact.description
}
Look at the format of your working command, no quotes around the type accelerator [ADSI] Then just apply that to your loop.
foreach($u in $pf)
{
$contact= [ADSI]"LDAP://$($u.Distinguishedname)"
$contact.description
}
foreach($u in $pf){$u.name;[ADSI]"LDAP://$($u.distinguishedname)"}
works ! thanks everybody for helping me :)

Make a dump of a session on fiddler without modification of Fiddler Rules

I want to do this things :
select a session
make a dump of this session (the issue is here)
Plus, I want to do that without modification of Fiddler Rules. I have done this with a modification of Fiddler Rules but the program will be used on several machines and it can be difficult to change Fiddler Rules in every machines.
I don't know if it is possible.
The code to do that with the modification of the fiddler Rules is :
PowerShell :
$filePath = "...\nameFile.txt" # file which contain the names of fiddler ZIP files
$file = Get-Content $filePath # content of nameFile
foreach ($line in $file) {
start $line # open the file
Write-Host "File : $line open"
Start-Sleep -s 1
}
& "...\Fiddler\ExecAction.exe" "failuresselection" # select all failures and make another file (see Fiddler Rules)
Fiddler Rules :
static function OnExecAction(sParams: String[]): Boolean {
[...]
// Select all failures and put them in a new ZIP file
case "failuresselection":
var path = "...\\Newlogs";
UI.actSelectSessionsWithResponseCode(449);
if (UI.GetFirstSelectedSession() != null){
UI.actSaveSessionsToZip(path+"\\Logs" + 449 + ".saz");
}
// Confirmation
FiddlerObject.StatusText = "Dumped all failures sessions to " + path;
UI.actExit();
return true;
[...]
}
I try this but it doesn't worked :
& "...\Fiddler\ExecAction.exe" "FiddlerApplication.UI.actSelectAll();"
It's to select all line but I think that ExecAction.exe replace QuickExec.
In summary, I am searching a way to do the same thing without modification of Fiddler Rules.

Remove specific xml elements using PowerShell

I have the following xml:
<NS1:PriceMaintenanceRequest xmlns:NS1="http://retalix.com/R10/services" MajorVersion="2" MinorVersion="0" FixVersion="0">
<NS1:Header>
<NS1:MessageId>1234</NS1:MessageId>
<NS1:Bulk UnitOfWork="false"/>
</NS1:Header>
<NS1:ProductPrice BusinessUnitId="9200" Action="AddOrUpdate">
<NS1:ProductId>2840000133</NS1:ProductId>
<NS1:Price Action="AddUpdate" Sequence="1234">
<NS1:UnitOfMeasureCode>EA</NS1:UnitOfMeasureCode>
<NS1:EffectiveDateTimestamp>2012-09-20T00:00:00</NS1:EffectiveDateTimestamp>
<NS1:EndDateTimestamp>2056-12-12T23:59:00</NS1:EndDateTimestamp>
<NS1:CatalogPrice Currency="USD">4.2900</NS1:CatalogPrice>
<NS1:BatchID>491364c5-73f5-45a4-8355-79cc0a720ea0</NS1:BatchID>
<NS1:ChangeStatus>NA</NS1:ChangeStatus>
</NS1:Price>
</NS1:ProductPrice>
<NS1:ProductPrice BusinessUnitId="90" Action="AddOrUpdate">
<NS1:ProductId>2840000133</NS1:ProductId>
<NS1:Price Action="AddUpdate" Sequence="1234">
<NS1:UnitOfMeasureCode>EA</NS1:UnitOfMeasureCode>
<NS1:EffectiveDateTimestamp>2012-09-20T00:00:00</NS1:EffectiveDateTimestamp>
<NS1:EndDateTimestamp>2056-12-12T23:59:00</NS1:EndDateTimestamp>
<NS1:CatalogPrice Currency="USD">4.2900</NS1:CatalogPrice>
<NS1:BatchID>491364c5-73f5-45a4-8355-79cc0a720ea0</NS1:BatchID>
<NS1:ChangeStatus>NA</NS1:ChangeStatus>
</NS1:Price>
</NS1:ProductPrice>
<NS1:ProductPrice BusinessUnitId="90" Action="AddOrUpdate">
<NS1:ProductId>2840000133</NS1:ProductId>
<NS1:Price Action="AddUpdate" Sequence="1234">
<NS1:UnitOfMeasureCode>EA</NS1:UnitOfMeasureCode>
<NS1:EffectiveDateTimestamp>2012-09-20T00:00:00</NS1:EffectiveDateTimestamp>
<NS1:EndDateTimestamp>2056-12-12T23:59:00</NS1:EndDateTimestamp>
<NS1:CatalogPrice Currency="USD">4.2900</NS1:CatalogPrice>
<NS1:BatchID>491364c5-73f5-45a4-8355-79cc0a720ea0</NS1:BatchID>
<NS1:ChangeStatus>NA</NS1:ChangeStatus>
</NS1:Price>
</NS1:ProductPrice>
</NS1:PriceMaintenanceRequest>
I need to remove all nodes with BusinessUnitId="90". So in this example, I end up with this:
<NS1:PriceMaintenanceRequest xmlns:NS1="http://retalix.com/R10/services" MajorVersion="2" MinorVersion="0" FixVersion="0">
<NS1:Header>
<NS1:MessageId>1234</NS1:MessageId>
<NS1:Bulk UnitOfWork="false"/>
</NS1:Header>
<NS1:ProductPrice BusinessUnitId="9200" Action="AddOrUpdate">
<NS1:ProductId>2840000133</NS1:ProductId>
<NS1:Price Action="AddUpdate" Sequence="1234">
<NS1:UnitOfMeasureCode>EA</NS1:UnitOfMeasureCode>
<NS1:EffectiveDateTimestamp>2012-09-20T00:00:00</NS1:EffectiveDateTimestamp>
<NS1:EndDateTimestamp>2056-12-12T23:59:00</NS1:EndDateTimestamp>
<NS1:CatalogPrice Currency="USD">4.2900</NS1:CatalogPrice>
<NS1:BatchID>491364c5-73f5-45a4-8355-79cc0a720ea0</NS1:BatchID>
<NS1:ChangeStatus>NA</NS1:ChangeStatus>
</NS1:Price>
</NS1:ProductPrice>
</NS1:PriceMaintenanceRequest>
How do i do it with PowerShell?
I need to load a files containing this xml from a directory, manipulate them, and save them.
Thanks a lot
You can do something like this:
Get-ChildItem -Path "C:\FolderWithXMLs" -Filter "*.xml" | ForEach-Object {
$path = $_.FullName
$xml = [xml](Get-Content $path)
$xml.PriceMaintenanceRequest.ProductPrice | ? { $_.BusinessUnitId -eq "90" } | % {
#Remove node
$xml.PriceMaintenanceRequest.RemoveChild($_)
}
$xml.Save($path)
}