/r/PowerShell
PowerShell is a cross-platform (Windows, Linux, and macOS) automation tool and configuration framework optimized for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models. PowerShell includes a command-line shell, object-oriented scripting language, and a set of tools for executing scripts/cmdlets and managing modules.
Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.
SUBREDDIT FILTERS
/r/PowerShell
I thought I had the script right but it is deleting users it shouldn't.
This is what I have:
$31DayUsers = Search-ADAccount -searchbase "ou=users,ou=disabled,dc=contoso,dc=com" -UsersOnly -AccountInactive -TimeSpan 31.00:00:00 | ?{$_.enabled -eq $false} | %{Get-ADUser $_.ObjectGuid} | select sAMAccountName
ForEach ($31DayUser in $31DayUsers) {
remove-aduser -Identity $31DayUser.sAMAccountName -Confirm:$false
}
I thought it was fine but users are getting deleted quicker than 31 days
I am confused for -ExpandProperty
, it seems to override the value when selected already exist. But when I access the overridden property directly, it returns the original value?
EDIT: I was reading this example, it says a NoteProperty
is appened to the new object after select. I actually kind of understand what it does, I guess Pet.Name
and Pet.Age
are overridden by john.Name
and john.Age
as NoteProperty
. But Out-String
seems to print the original value of Pet which causes the problem I met. Is it correct?
$john = @{
Name = 'John Smith';
Age = 30;
Pet = @{
Name = 'Max';
Age = 6
}
}
$john | select Name, Age -ExpandProperty Pet # property override by Pet?
Name Value
---- -----
Age 6
Name Max
($john | select Name, Age -ExpandProperty Pet).Name # while if I access the Name it returns the original
John Smith
I have a problem at work.
I need to run powershell scripts on the computer in the user context. Right now all scripts are blocked by the applocker. One solution might be to sign the "good" scripts and use the allsigned execution policy.
But our security man is no friend of it, since there are so many trusted root ca in our system.
Is there any way to combine the execution policy with a few select root ca and not the whole list that is saved
any help is appreciated
ExchangeOnlineMangement PS Module.
Context & Background:
I have an automation script that has been happily running every day for over 3 years without issue that finds users that don't have a default address book and assigns one (details completely irrelevant to this issue)
On the 11th October, a colleague who is not well versed in PS needed to run a Rubrik sizing script for managerial reporting purposes, this script spat out some informational that a few PS modules were required to complete correctly and amongst these were the ExchangeOnlineManagement Module (which was already installed). As he just blindly followed the script and installed it, it installed the latest version 3.6.0 (sadly our backup policy on this server doesn't go back far enough for me to do a restore and find the original module version I was using).
Since carrying out that action, my scheduled task that carries out my automation script broke.
The script code directly pertinent to the issue is:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# CONNECT TO EXCHANGE ONLINE #
Connect-ExchangeOnline -CertificateThumbprint $CertificateThumbPrint -AppId $appID -Organization $tenantID
$mailboxes = $null
$mailboxes = Get-EXOMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited -Properties userPrincipalName, AddressBookPolicy, WhenCreated -Filter "whenCreated -gt '$((Get-Date).AddDays(-1))'" | Where-Object { $_.userPrincipalName -match 'st[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' -and $_.AddressBookPolicy -like "" } | Select-Object -Property userPrincipalName, AddressBookPolicy, whenCreated
when this script runs now I get the following error on the Get-EXOMailbox line:
Microsoft.OData.Client.DataServiceTransportException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ArgumentException: The specified value is not valid in the 'SslProtocolType' enumeration.
Parameter name: sslProtocolType
at System.Net.Security.SslState.ValidateCreateContext(Boolean isServer, String targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, Boolean remoteCertRequired, Boolean checkCertRevocationStatus, Boolean checkCertName)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.OData.Client.HttpWebRequestMessage.GetResponse()
--- End of inner exception stack trace ---
at Microsoft.OData.Client.HttpWebRequestMessage.GetResponse()
at Microsoft.OData.Client.DataServiceContext.GetResponseHelper(ODataRequestMessageWrapper request, IAsyncResult asyncResult, Boolean handleWebException)
at Microsoft.OData.Client.QueryResult.ExecuteQuery()
at Microsoft.OData.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)
at Microsoft.Exchange.Management.AdminApiProvider.ApiProvider`1.<>c__DisplayClass36_0.<InvokeRestApiWithRetry>b__1()
at Microsoft.Exchange.Management.AdminApiProvider.ApiProvider`1.ProcessWithRetry[TRetType](Func`1 queryExecutor, Container context, String requestURL, DataServiceContext dataServiceContext)
at Microsoft.Exchange.Management.AdminApiProvider.ApiProvider`1.<InvokeRestApiWithRetry>d__36.MoveNext()
at Microsoft.Exchange.Management.AdminApiProvider.AsyncJobController`1.<>c__DisplayClass12_0.<InvokeQuery>b__0(ApiProvider`1 apiProvider)
at Microsoft.Exchange.Management.AdminApiProvider.ApiProvider`1.InvokeQuery(ApiProviderContext`1 apiProviderContext, Func`2 responseHandler)
at Microsoft.Exchange.Management.AdminApiProvider.AsyncJobController`1.InvokeQuery(ApiProviderContext`1 queryContext, Action`1 writeObject, Action`1 writeError)
at Microsoft.Exchange.Management.RestApiClient.AdminCmdlet`2.<ProcessRecord>b__34_0()
at Microsoft.Exchange.Management.RestApiClient.AdminCmdlet`2.ExecuteWithExceptionHandling(Action action, Exception& exception)
the script still connects successfully to Exchange Online as it always did but errors when collecting the Get-EXOMailbox data.
However,
This is weird because I have already called Tls12 at the beginning of the script and so it is already using TLSv1.2
I have also permanently set strong cryptography at the OS level as outlined here - https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2?view=exchange-ps#updates-for-version-300-the-exo-v3-module and the issue still persists.
so the issue appears to be related to PSv5.1
Any ideas on what is causing this as while I have 'fixed' it with a workaround of changing the script to use PowerShell v7, I still want to find the root cause and fix it properly.
SMALL UPDATE
found another user with what appears to be the exact same issue - https://answers.microsoft.com/en-us/msoffice/forum/all/exo-cmdlet-issue/e621a862-4b00-4966-9afd-a2a672253b6f
Also to note, I tried Office365 support and they refused to support it as it was a, and i quote, "custom script" so MS support was of no use.
Hello
We're not able to connect to Security & Compliance PowerShell using an AppId and Certificate. We've tried:
The application service principal is assigned "Security Reader" role.
We get the error (as of recently, we believe) when using the command:
Connect-IPPSSession -CertificateThumbprint "xxx" -AppId "xxx" -Organization "xxx.onmicrosoft.com"
The error we receive: OperationStopped: An error has occurred.
VERBOSE: Returning precomputed version info: 3.6.0
VERBOSE: ModuleVersion: 3.6.0
VERBOSE: [ThreadID: #] Trying to get a new token from AAD
VERBOSE: [ThreadID: #] Trying to acquire token based on UI flow
VERBOSE: [ThreadID: #] Successfully acquired new token for Cert based flow.
VERBOSE: [ThreadID: #] Successfully got a token from AAD
----------------------------------------------------------------------------------------
We have made updates to move the SCC admin experience to REST-based APIs. In doing so, we will be deprecating the legacy Remote PowerShell (RPS) protocol starting July 15, 2023.
Benefits of REST-based cmdlets: improved security, WinRM no longer required for client-server communication, improved error handling.
The REST API has the same cmdlets available and feature parity with RPS(V1) cmdlets, so existing scripts and processes don't need to be updated. Simply using the new module will ensure REST is used rather than RPS.
For more information, go to
----------------------------------------------------------------------------------------
VERBOSE: ConnectionContext Removed
OperationStopped: An error has occurred.https://aka.ms/exov3-module
Which doesn't really tell us much. If we try to dig into the error object, we get a little more, but we haven't been able to figure out what could possibly be the issue.
$Error[0].Exception
TargetSite : Void ProcessRecord()
Message : An error has occurred.
Data : {}
InnerException :
HelpLink :
Source : Microsoft.Exchange.Management.ExoPowershellGalleryModule
HResult : -2146233087
StackTrace : at Microsoft.Exchange.Management.ExoPowershellSnapin.NewEXOModule.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
$Error[0].InvocationInfo
MyCommand : New-EXOModule
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 656
OffsetInLine : 39
HistoryId : 22
ScriptName : C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netCore\ExchangeOnlineManagement.psm1
Line : $ImportedModule = New-EXOModule -ConnectionContext $ConnectionContext -SkipLoadingFormatData:$SkipLoadingFormatData;
Statement : New-EXOModule -ConnectionContext $ConnectionContext -SkipLoadingFormatData:$SkipLoadingFormatData
PositionMessage : At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netCore\ExchangeOnlineManagement.psm1:656 char:39
+ … tedModule = New-EXOModule -ConnectionContext $ConnectionContext -Skip …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot : C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netCore
PSCommandPath : C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netCore\ExchangeOnlineManagement.psm1
InvocationName : New-EXOModule
PipelineLength : 0
PipelinePosition : 0
ExpectingInput : False
CommandOrigin : Internal
DisplayScriptPosition :
$Error[0].CategoryInfo
Category : NotSpecified
Activity : New-EXOModule
Reason : SystemException
TargetName :
TargetType :
$Error[0].ScriptStackTrace
at Connect-ExchangeOnline<Process>, C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netCore\ExchangeOnlineManagement.psm1: line 656
at Connect-IPPSSession<Process>, C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netCore\ExchangeOnlineManagement.psm1: line 904
at <ScriptBlock>, <No file>: line 1
Does anyone have the same issue as of recently? Any help is much appreciated. Have a nice day!
Hi All,
I have this variable $pimroles which is an array - Object[]. I want to output this to a CSV file to "C:\temp\pimroles.csv".
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
The contents of the variable are below.
DisplayName Id IsPrivileged IsEnabled
----------- -- ------------ ---------
App registration administrator custom role fa85b348-b5a2-491a-8e82-6bd76e04747e True True
Application Administrator 9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3 True True
Application Developer cf1c38e5-3621-4004-a7cb-879624dced7c True True
Authentication Administrator c4e39bd9-1100-46d3-8c65-fb160da0071f True True
Authentication Extensibility Administrator 25a516ed-2fa0-40ea-a2d0-12923a21473a True True
B2C IEF Keyset Administrator aaf43236-0c0d-4d5f-883a-6955382ac081 True True
Cloud Application Administrator 158c047a-c907-4556-b7ef-446551a6b5f7 True True
Cloud Device Administrator 7698a772-787b-4ac8-901f-60d6b08affd2 True True
Conditional Access Administrator b1be1c3e-b65d-4f19-8427-f6fa0d97feb9 True True
Directory Writers 9360feb5-f418-4baa-8175-e2a00bac4301 True True
Domain Name Administrator 8329153b-31d0-4727-b945-745eb3bc5f31 True True
External Identity Provider Administrator be2f45a1-457d-42af-a067-6ec1fa63bc45 True True
Global Administrator 62e90394-69f5-4237-9190-012177145e10 True True
Global Reader f2ef992c-3afb-46b9-b7cf-a126ee74c451 True True
Helpdesk Administrator 729827e3-9c14-49f7-bb1b-9608f156bbb8 True True
Hybrid Identity Administrator 8ac3fc64-6eca-42ea-9e69-59f4c7b60eb2 True True
Intune Administrator 3a2c62db-5318-420d-8d74-23affee5d9d5 True True
Lifecycle Workflows Administrator 59d46f88-662b-457b-bceb-5c3809e5908f True True
Partner Tier1 Support 4ba39ca4-527c-499a-b93d-d9b492c50246 True True
Partner Tier2 Support e00e864a-17c5-4a4b-9c06-f5b95a8d5bd8 True True
Password Administrator 966707d0-3269-4727-9be2-8c3a10f19b9d True True
Privileged Authentication Administrator 7be44c8a-adaf-4e2a-84d6-ab2649e08a13 True True
Privileged Role Administrator e8611ab8-c189-46e8-94e1-60213ab1f814 True True
Security Administrator 194ae4cb-b126-40b2-bd5b-6091b380977d True True
Security Operator 5f2222b1-57c3-48ba-8ad5-d4759f1fde6f True True
Security Reader 5d6b6bb7-de71-4623-b4af-96380a352509 True True
User Administrator fe930be7-5e62-47db-91af-98c3a49a38b1 True True
I am running the following:
$pimroles | Export-Csv -Path C:\temp\PIMRoles.csv -NoTypeInformation
However it is producing a strange output with some header and tagging information. The formatting is stuffed when I paste in Reddit, but essentially the content isn't there.
|| || |ClassId2e4f51ef21dd47e99d3c952918aff9cd|pageHeaderEntry|pageFooterEntry|autosizeInfo|shapeInfo| |033ecb2bc07a4d43b5ef94ed5a35d280|Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo| |9e210fe47d09416682b841769c78b8a3||
Aside from exporting to a text file with this, then manually editing - what else can I try?
$pimroles > C:\temp\PIMRoles.txt
I need a way to find all files with the word "update" anywhere within the .cfg files in my /configs/ folder
I am trying to get better at unit testing and have come up with a bunch of Pester questions - I went looking on the official Pester site, bought a book, the site mentioned #testing on the PowerShell Discord, but I got no replies to my questions there, just someone joking that I needed 'Tier 2 support.' Hoping someone here can help with a few of these!
First question is about running Pester v4 and v5 simultaneously / selectively:
- I'm in an environment where there are a lot of internally-developed PowerShell modules. Right now, they still use Pester v4 as part of the build / test / publish / deploy process. Is there a way to start using Pester 5 (maybe only on newer modules?) without breaking the existing process, and without having to 'lift and shift' all of the modules and their tests at the same time?
Some of the ways we've considered going about this are:
Next question is about using the same 'base module file' test as a template, referenced from multiple module directories? (Pester v5)
- We write one .ps1 file per function, and those files are grouped into a Public and a Private folder for each module. There is another Tests folder next to those, where we want to write at least one 'verb-functionname.tests.ps1' file as well. But we also have a general 'every module should pass these basic tests' file, both for all of the individual .ps1 files, as well as for the .psm1 and .psd1 files after assembled.
In the spirit of Don't Repeat Yourself (DRY): rather than copying that file into every module subfolder (and updating every copy if our across-the-board test criteria changes), is there a best-practice way that we could call Invoke-Pester on all of the files in a specific module's test folder, but also to include this 'everyModule.Tests.ps1' test file into the same context / container as it evaluates the module? (Or should we just make a copy of that base file, because that is a best practice in this case, to make each set of tests independent of any other modules' folders?)
Last questions are about using Pester with VS Code:
- When I open a folder in VS Code, it has our whole repository of PowerShell modules, each in its own subfolder. But when I click the Testing (beaker) icon, it finds all of the verb-command.tests.ps1 files from all subfolders and displays them all alphabetically, but in one long list so I don't know which is which. Is there a way to change a setting for the extension so it will preserve or display the containing folder paths before each one? Or do I just have to stick to only opening that one subfolder when I want to run tests on that module? (I will sometimes be editing one module and need to make a corresponding edit to another one at the same time.)
- When I try to debug during Invoke-Pester, I will set breakpoints in the functions in a module, and/or in the .tests.ps1 files, to try and see the state of certain variables at one specific moment. I can sometimes get to a place where I can see the values of variables, have my 'aha, duh' moment, and go fix it. But all too frequently, one of two things happens instead (or both):
Any helpful suggestions, pointers to existing code to study, etc would be greatly appreciated!
Hi all
I have started learning the basics of Powershell. I watched a 2hr course on Pluralsight from Michael Bender which teaches the basics, how to use help, get-command, get-member, how to use the file system, pipe and variables.
What’s another video course (don’t fancy learning through textbooks) that i can use to build on that slowly? Any ideas on resources for taking the next step although not jumping in to deep?
Hope that makes sense and all help greatly appreciated!
Hi, I am new to pwsh. I've found that $pwd
is a PathInfo
, but I was able to do:
[IO.Path]::Combine($pwd, 'path/to/target.foo')
# or something like
ni "$pwd/foo.txt"
Does pwsh implicitly called ToString()
when it was applied to a string parameter? Or is there an annotation required to enable the behaviour for a function?
I did a little search but didn't find the anwser, thanks for any sharing!
Help requested to mass rename and replace the title of mp3 files with File Name.
Can you please help with a powershell script? Thanks
Hello, I have a script adding empty .exe files (named after each folder) to all folders within a specified drive (Z:\). Would there be any way to add a line(s) that makes it ignore subfolders? (i.e. any folders beyond the first set of folders in the drive).
$drivePath = "Z:\"
$directories = Get-ChildItem -Path $drivePath -Directory -Recurse
foreach ($dir in $directories) {
$folderName = $dir.Name
$exePath = Join-Path -Path $dir.FullName -ChildPath "$folderName.exe"
New-Item -Path $exePath -ItemType File -Force
Write-Output "Created $exePath"
}
Write-Output "Script execution completed."
I have a Windows lab server and Windows 10, which needs to be updated every month I've been testing the PSWindowsUpdste module for a while but it doesn't seem consistent to me The loop is caught, it does not advance Any recommendations? What are you currently using?
indeed you can go through the gui, sound setting but its a pita!
I am attempting to create a Powershell module that will facilitate daily, weekly, and monthly back ups (son/father/grandfather).
It will be able to run full and incremental backups TO&FROM any file storage location chosen. It will have; logging for successes and failures, a cmdlet to schedule events in the appropriate time slots, a cmdlet to restore individual items or an entire backup set, a cmdlet to purge all versions of an item or backup sets based on what is needed/wanted.
I have a few of the background functions written, but the core utility is going to be a major PITA.
My main reason for reaching out is to see if anyone would actually use it? Or what features it would need to be usable or semi easily adoptable. I don’t love that the only decent backup solution that I’ve found for network drives in particular is Veeam: I know the community edition is free with a custom domain and I know there are probably other solutions but most cost $$ and I’m prude.
P.S. if it’s a shit idea or it was done better by someone else let me know.
Windows OS (windows 11). As per title.
I want to run a python script on shutdown. I am using Task Scheduler right now (don't know if there is a better option).
Currently, it is set to Log: System, Source: User32, Event ID: 1074.
However, the OS does not wait for the script to finish its execution and shuts down immediately. This leads to BSOD and invalid index.lock files on boot.
How to allowing the script to run to completion before shutting down?
I've been scripting for over 15 years now. As a Windows system administrator, I initially worked with VBS and have transitioned to PowerShell for nearly the last decade.
I'm not sure if it's just me or a common experience, but I used to write code—sometimes just a few lines—and ensure it functioned correctly by testing on various devices, from development to UAT, and gradually moving to production.
Recently, I've joined a new organization that emphasizes a very structured approach to scripting. While this has been a bit challenging, I'm eager to adapt because I believe it will enhance my skills.
Do you have any suggestions that could assist me in this transition?
I've been considering creating something that focuses on formatting, case sensitivity options, and an approved list of verb-noun combinations for scripts. I know that VS Code can help with formatting, but it doesn't always catch everything, like multiple blank lines.
If you have any recommendations, resources, or links that could be helpful, I would greatly appreciate it!
I made a powershell script GUI that attempts to recreate and extend the functionality of problem Step Recorder in windows. It's created using csharp and powershell. Looking for feedback. Anything is welcome.
https://github.com/schrebra/Problem-Step-Recorder-Plus-Plus
This is a modernized replacement for Microsoft's Problem Steps Recorder (PSR), which was discontinued in newer Windows versions. PSR was a valuable tool that IT professionals and users relied on to document technical issues.
Fill the Gap
Improved Features
Think of it like a super-powered version of the Windows Snipping Tool, but with extra features that make it especially useful for anyone who needs to regularly document things they're doing on their computer.
This is a powerful screenshot tool that lets you:
Organized Storage
Flexible Capture Options
Professional Features
Windows API Integration
Global Settings
Capture Options
File Management
I've been using PowerShell for the last couple of months consistently and have been getting into creating scripts for my team at work. Something that I've gone back and forth on is how to reduce issues with people not running the scripts as admin. I'm curious what solutions are out there that I maybe haven't come across.
Personally, I've created shortcuts for my scripts that run the .ps1 as admin, but sometimes people run the .ps1 directly and issues can arise from that. I've also tried adding code to rerun the .ps1 as admin, and it works well enough, but sometimes weird issues can arise with the arguments.
Do you add code to the script to rerun as admin if it detects a non-admin PS session? Do you just put a banner message that says to run the script as admin? Do you just write the script and just advise your teammates that they should always run the scripts as admin?
I have a list of approx 200 URLs I need to download the images from. I'd like each URL to generate a folder and save the images in there, as opposed to them all going in the same folder.
I managed to figure out how to download from a singular website (thanks to u/RandyCoreyLahey)
$wc = New-Object System.Net.WebClient
$req = Invoke-WebRequest -Uri "https://www.url.com"
$images = $req.Images | Select -ExpandProperty src
$count = 0
foreach($img in $images){
$wc.DownloadFile($img,"C:\Users\me\Downloads\images\img$count.jpg")
$count++
}
But adapting this to my needs is probably beyond my skill level currently. The URLs are stored in a text file called "urls.txt" in my Downloads folder.
Hi all,
I need to download images from a webpage, I will have to do this for quite a few web pages, but figured I would try get it working on one page first.
I have tried this, and although it is not reporting any errors, it is only generating one image. (Using BBC as an example). I am quite a noob in this area, as is probably evident.
$req = Invoke-WebRequest -Uri "https://www.bbc.co.uk/"
$req.Images | Select -ExpandProperty src
$wc = New-Object System.Net.WebClient
$req = Invoke-WebRequest -Uri "https://www.bbc.co.uk/"
$images = $req.Images | Select -ExpandProperty src
$count = 0
foreach($img in $images){
$wc.DownloadFile($img,"C:\Users\xxx\Downloads\xx\img$count.jpg")
}
I want to write a .reg file, to include the code below, and I want Powershell to run it.
I tried converting each line to Powershell, and for some reason, something's not working, but when I manually run the .reg file from the command prompt, it does what it suppose to do. That is, an elevated command prompt.
How can I make Powershell write this .reg file and run it?
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\exefile\shellex\ContextMenuHandlers\PintoStartScreen]
@="{470C0EBD-5D73-4d58-9CED-E91E22E23282}"
[HKEY_CLASSES_ROOT\Folder\ShellEx\ContextMenuHandlers\PintoStartScreen]
@="{470C0EBD-5D73-4d58-9CED-E91E22E23282}"
[HKEY_CLASSES_ROOT\Microsoft.Website\shellex\ContextMenuHandlers\PintoStartScreen]
@="{470C0EBD-5D73-4d58-9CED-E91E22E23282}"
[HKEY_CLASSES_ROOT\mscfile\shellex\ContextMenuHandlers\PintoStartScreen]
@="{470C0EBD-5D73-4d58-9CED-E91E22E23282}"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]
"{470C0EBD-5D73-4d58-9CED-E91E22E23282}"=-
Hello, I am attempting to write a script on PowerShell that will take files from a SharePoint site and download/update them locally as needed.
The plan is to deploy via intune however we would prefer for this script to have as little interaction with user as possible (client end aren’t tech savvy nor will they care to login to a terminal everyday).
When running “Connect-PnPOnline -Url “myComp.sharepoint.com/sites/Folder” -UseWebLogin” it works as expected but then I tried to use -Credentials within the username and password and no MFA however it keeps asking to register the app with the tenant, and Azure does not seem to have that anymore due to security reasons, or maybe I’m just blind.
Ether way any suggestions on how to get this done or point to a better direction would be appreciated.
Hi, for some reason syntax check doesnt work in vscode neigher in powershell ise. Im doing something wrong or powershell just lack of this functionality?
For example:
Write-Hoooost "sdf"
dont trigger any syntax error (
Thanks
Hello,
I am not much of a programmer, but I have been working on a fun project for myself lately. I have everything working except when I go to automate it. I am using windows task scheduler, using my local account and set to Run whether user is logged on or not. The reason for this is so that I do not have PS windows open every five minutes and mess up what I am doing. For the life of me, I cannot figure out why this configuration prevents me from running
[Win32.Wallpaper]::SetWallpaper($imgPath)
at the end.
It works when I run the script manually, but not when I run it through task scheduler. I am sure that the script is being run as my personal account and should have access to that but I can provide more details as needed, but the file is a mess so I should probably clean that up while I wait :)
This process is triggered when you call fail to provide a value to mandatory parameter. I would much prefer, if the command failed with an error instead being locked into this strange context that I always force exit.
I looked at the preference variables in the docs and nothing seems to apply. Am on pwsh 7.4
Hello everyone,
Today I Had to Work with a HP ILO Module.
When I wanted to use a Set- Cmdlt and Set an Array of IP Addresses IT didnt Work.
For example
SNTPServers = @("0.0.0.0", "1.1.1.1") Set-SNTP -connection $con -SNTPServer $SNTPServers
It complained about an additional Parameter and would only Set the first IP Address of the Array.
After researching the specific HPEilo cmdlt Error I learned to use the Array Like
SNTPServers = ,@("0.0.0.0", "1.1.1.1")
(Comma before the @)
What is actually going in here?
I know these cmdlts are Just abstracted Rest APIs, but I have never encounterd this Problem.
Or after all is it Just a weird bug in the Module?
Thanks for your answers :)
I have the following script that nicely finds IE startup page settings but Edge's GPOs are much more complex and it doesn't work for find them.
ETA: Pastebin link https://pastebin.com/gGftvMRu
# Define the string to search for
$searchString = "Homepage"
# Get the domain name
$domainName = $env:USERDNSDOMAIN
# Import the Group Policy module
Import-Module GroupPolicy
# Get all GPOs in the domain
$allGPOs = Get-GPO -All -Domain $domainName
# Initialize an array to store matched GPOs and their settings
$matchedGPOs = @()
# Search each GPO for the specified string
foreach ($gpo in $allGPOs) {
$report = Get-GPOReport -Guid $gpo.Id -ReportType Xml
#Write-Host "Report for GPO: $($gpo.DisplayName)" -ForegroundColor Yellow
#Write-Host $report # Debugging line
if ($report -match $searchString) {
[xml]$xmlReport = $report
$mySettings = $xmlReport.SelectNodes("//*[contains(@id, '$searchString')]")
if ($mySettings.Count -gt 0) {
Write-Host "Match found in: $($gpo.DisplayName)" -ForegroundColor Green
foreach ($setting in $mySettings) {
$matchedGPOs += [PSCustomObject]@{
GPO = $gpo.DisplayName
Setting = $setting.OuterXml
}
}
} else {
Write-Host "No specific setting found in: $($gpo.DisplayName)" -ForegroundColor Red
}
}
}
# Output the results in a table format
$matchedGPOs | Format-Table -AutoSize
Has anyone done something like this? Parsing the XML seems to be where I'm falling apart
Has anyone integrated their powershell scripts with Opentelemetry?
I was looking for a standard way to monitor the run time of scripts and sub components.
spans and traces seem to be "the way"
i'm new to opentelemtry but it doesnt look like they have anything native for powershell. anyone do anything creative here? using the .NET imported into the powershell script etc?
trying to get this going without starting from zero.
the other plus with opentelemtry for this is that it would feed into our LogicMonitor dashboard with all our other stats.
thanks in advance
Gd.