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. ;-)
Related
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
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
$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 :)
not sure if I'm chaing the wild goose here but as per subject I'd need to get a list of AD attributes, for the user ObjectClass, that are multie valued.
For example the proxyAddresses exchange specific attribute is multi valued where extensionAttribute* only accept a single string.
We use a heavily customized schema and while I could go through each attribute documentation I'd rather get a list of aforementioned attributes via PowerShell.
I've tried using ldp.exe but could not achive desired results and was wondering if there is a way to do this via PowerShell or .Net managed code.
Thanks in advance for any help/pointer.
So you have to query the Schema part of the directory and look for objectClass attributeSchema and attribute isSingleValued (FALSE). The part of the distinguichName wichh is invariant is : CN=Schema,CN=Configuration.
try first with CSV :
csvde -f MultivaluedAttributes.csv -d CN=Schema,CN=Configuration,DC=MySubdomain,DC=MyDomain,DC=com -r "(&(objectclass=attributeSchema)(isSingleValued=FALSE))" -l lDAPDisplayName
Here is the powershell code.
# LDAPSchemaQuery.PS1
try
{
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://179.22.21.01/CN=Schema,CN=Configuration,DC=MyDomain,DC=MyExt","MyUser", 'MyPassword')
# Query into the Schema
# csvde -f MultivaluedAttributes.csv -d CN=Schema,CN=Configuration,DC=office,DC=coyotesystems,DC=com -r "(&(objectclass=attributeSchema)(isSingleValued=FALSE))" -l lDAPDisplayName
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
#$Rech.filter = "(&(objectclass=user)(mail=*)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))"
$Rech.filter = "(&(objectclass=attributeSchema)(isSingleValued=FALSE))"
$Rech.SearchScope = "subtree"
$dumy=$Rech.PropertiesToLoad.Add("lDAPDisplayName")
$adAttributes = $Rech.findall()
foreach ($adAttribute in $adAttributes)
{
$multivaluedAttribute = try{$adAttribute.Properties["lDAPDisplayName"]}catch{""}
$multivaluedAttribute
}
}
catch
{
Write-Verbose "LDAPSchemaQuery : PB with $($adAttribute.Path)"
}
I have need of retrieving and inspecting the delegate forwarding rule (the built-in delegate commands in EWS being inadequate for my needs since they choke on groups being used as delegates).
I am able to successfully locate the rule created by "Schedule+ EMS Interface". However, I am unable to retrieve PR_RULE_ACTIONS. Turning on tracing.
I see that the PidTagRuleMsgProvider property is getting returned just fine, but PR_RULE_ACTIONS never does.
I suspect that I am using the wrong MAPI property type in the propertyset definition, but I've gone through everything listed at http://msdn.microsoft.com/en-us/library/exchangewebservices.mapipropertytypetype(v=exchg.140).aspx . Any clues?
Here is the relevant snippet of code:
# Setup Basic EWS Properties for Message Search - Used to locate Hidden Forwarding Rule
$searchFilterForwardRule = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Rule", [Microsoft.Exchange.WebServices.Data.ContainmentMode]::Prefixed, [Microsoft.Exchange.WebServices.Data.ComparisonMode]::Exact)
$itemViewForwardRule = New-Object Microsoft.Exchange.WebServices.Data.ItemView(30, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::Beginning)
$itemViewForwardRule.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, [Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
$itemViewForwardRule.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
# Properties for Hidden Delegate Forwarding Rule
$PID_TAG_RULE_MSG_PROVIDER = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65EB,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
$PID_TAG_RULE_ACTIONS = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6680,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
# Property Set for Delegate Forward Rule
$propertySetForwardRule = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, $PID_TAG_RULE_MSG_PROVIDER)
$forwardRuleExists = $false
$findResults = $service.FindItems([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $searchFilterForwardRule, $itemViewForwardRule)
If ($findResults.TotalCount -lt 1) {
Write-Error "Failed to find rule" "Error"
} Else {
Foreach ($item in $findResults.Items) {
$item.Load($propertySetForwardRule)
If ($item.ExtendedProperties.Count -ge 1) {
If ($item.ExtendedProperties[0].Value -eq "Schedule+ EMS Interface") {
$forwardRuleExists = $true
write-host "Delegate forwarding rule found." -ForegroundColor Cyan
$propertySetForwardRule.Add($PID_TAG_RULE_ACTIONS)
$item.Load($propertySetForwardRule)
Write-Host "Attempting to retrieve x6680 PR_RULE_ACTIONS (PidTagRuleActions)" -ForegroundColor Cyan
$PR_RULE_ACTIONS = $null
if($Item.TryGetProperty($Pid_Tag_Rule_Actions,[ref]$PR_RULE_ACTIONS)){
return $PR_RULE_ACTIONS
} # endif
else {write-host "TryGetProperty for PR_RULE_ACTIONS failed!" -ForegroundColor Red
} # endelse
} # End If - Correct Message
} # End If - Has Extended Properties
} # End ForEach
} # End If - Message Count
Glen Scales was able to set me on the right path. It turns out that PR_RULE_ACTIONS is not exposed via EWS, but the same data exposed via an attribute called PR_EXTENDED_RULE_ACTIONS. Now I'm happily slinging code to parse the binary blob.
http://msdn.microsoft.com/en-us/library/ee218391(v=EXCHG.80).aspx
The property tag for PR_RULE_ACTIONS is 0x668000FE. You can see it (and the property data) in OutlookSpy (I am its author) - go to the Inbox folder, click IMAPIFolder button, go to the PR_RULES_TABLE tab, select the rule, double click on the PR_RULE_ACTIONS property.
Note that PT_ACTIONS MAPI type (0x000FE) is only accessing in Extended MAPI, I don't think EWS will be able to return it.