/r/PowerShell

Photograph via snooOG

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.

ABOUT POWERSHELL

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

Desired State Configuration

Unanswered Questions

Solved Questions

News

Information

Script Sharing

Daily Post

Misc








/r/PowerShell

264,883 Subscribers

2

Unable to connect with Connect-IPPSSession using AppId and Certificate

Hello

We're not able to connect to Security & Compliance PowerShell using an AppId and Certificate. We've tried:

  • Multiple tenants
  • PowerShell v5 and v7
  • Windows and Ubuntu

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!

0 Comments
2024/11/18
07:57 UTC

3

Export-CSV not outputting csv with correct data

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 
6 Comments
2024/11/18
05:35 UTC

1

Locate text in the content of multiple .cfg files

I need a way to find all files with the word "update" anywhere within the .cfg files in my /configs/ folder

4 Comments
2024/11/18
01:23 UTC

8

Pester Questions - 'Tier 2 Support'

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:

  • Loading two instances (one of v4, one of v5) and using module prefixes when we import-module so we could do like 'invoke-v4Pester';
  • Tweak our test process to look at the module manifest and maybe utilize a maximumversion 4.9.9 to test the older modules;
  • If we had to limit all of the newer testing to a separate branch, using git hooks (like post-checkout) to somehow change which version of the Pester module we load (seems like a PITA);
  • Since Pester v5 will display warnings like "you're calling invoke with v4 style arguments", is there a way to use those detection methods (either on the invoke call or on looking at the test files) and decide to run v4 for the older ones, until we can get them all updated?

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):

  1. I get lost in the Pester module itself when trying to step in and out of our code or tests files, and/or...
  2. Because Pester is dynamically creating containers, spawning new PowerShell instances (etc), I don't know how/if I can tell Pester or VS Code to 'allow debug connections' to those containers, in order to peer into them and see what's going on.

Any helpful suggestions, pointers to existing code to study, etc would be greatly appreciated!

1 Comment
2024/11/18
00:34 UTC

8

Noob question

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!

19 Comments
2024/11/17
21:52 UTC

3

Is there a implicit evaluation for PathInfo to string?

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!

7 Comments
2024/11/17
21:07 UTC

0

Bulk rename mp3 files title with name of file

Help requested to mass rename and replace the title of mp3 files with File Name.

Can you please help with a powershell script? Thanks

16 Comments
2024/11/17
20:49 UTC

4

Help with script adding "name" files to empty folders

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."
5 Comments
2024/11/17
18:15 UTC

3

Windows Updates

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?

17 Comments
2024/11/17
10:18 UTC

0

a way to disable all windows sounds?

indeed you can go through the gui, sound setting but its a pita!

5 Comments
2024/11/17
09:54 UTC

3

Backup solution?

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.

25 Comments
2024/11/17
04:36 UTC

2

Allowing a script to run to completion before shutting down

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?

12 Comments
2024/11/17
03:55 UTC

24

How to better Script?

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!

11 Comments
2024/11/16
22:21 UTC

33

Problem Step Recorder ++

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

Background

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.

What Was PSR?

  • A built-in Windows tool that recorded step-by-step actions
  • Used to document computer problems for tech support
  • Automatically captured screenshots of each action
  • Created an MHTML report with images and descriptions
  • Widely used in enterprise IT departments

Why PSR++ Was Created

  1. Fill the Gap

    • PSR's discontinuation left many users without a reliable alternative
    • Organizations still need a way to document technical issues
    • Support teams require detailed problem documentation
  2. Improved Features

    • More control over capturing process
    • Better organization of screenshots
    • Enhanced mouse tracking and highlighting
    • Modern interface and capabilities
    • More flexible output options

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.

What It Does

This is a powerful screenshot tool that lets you:

  • Take screenshots of your screen or specific windows
  • Highlight where your mouse is pointing
  • Capture multiple screenshots automatically
  • Save screenshots in organized folders by date/time

Why It's Useful

For Regular Users

  • Better than basic Print Screen when you need to:
    • Document steps in a process
    • Show someone how to do something on a computer
    • Save proof of something you saw on screen
    • Create training materials
    • Report software bugs

For Professional Use

  • Perfect for:
    • Creating technical documentation
    • Making user guides
    • Recording work procedures
    • Quality assurance testing
    • Customer support interactions
    • Training materials

Key Benefits

  1. Organized Storage

    • Automatically saves files in dated folders
    • Never lose track of your screenshots
  2. Flexible Capture Options

    • Take one screenshot or many
    • Choose exactly what to capture
    • Show where your mouse is pointing
  3. Professional Features

    • Timer options for perfect timing
    • Mouse highlighting for clear instructions
    • Clean, organized output

Core Features

  • Advanced screenshot capture capabilities
  • Mouse cursor highlighting and tracking
  • Customizable capture settings
  • Session-based screenshot organization
  • Multiple capture modes (single/continuous)

Technical Components

  1. Windows API Integration

    • User32.dll imports for window/cursor management
    • Screen coordinate handling
    • Window detection and manipulation
  2. Global Settings

    • Screenshot storage path management
    • Capture session tracking
    • Mouse highlight customization
    • Capture counter and session ID generation
  3. Capture Options

    • Countdown timer functionality
    • Continuous capture mode
    • Mouse cursor visualization
    • Highlight colors and opacity settings
    • Custom outline colors
  4. File Management

    • Automatic directory creation
    • Session-based folder organization
    • Screenshot naming conventions

Implementation Details

  • Written in PowerShell
  • Uses Windows Forms and Drawing assemblies
  • Leverages P/Invoke for native Windows API calls
  • Includes base64-encoded icon data
  • Implements strict mode for error handling

Future Change Log

  • [Fix] - Remove small boarder around screenshots
  • [Feature] - Add screenshot outline color and size. Include toggle as well
  • [Improvement] - Hide preview pane until screenshot is captured
  • [Feature] - Include settings menu bar to export profile configured settings to program path.
  • [Feature] - Include settings menu bar for import configured profile settings.
  • [Feature] - Create cfg file for overall settings to auto import from last session
  • [Bug] - Fix clipboard screenshot when copying into markdown - It slightly shrinks the screenshot
7 Comments
2024/11/16
21:44 UTC

63

How do you handle forcing scripts to run as admin?

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?

48 Comments
2024/11/16
20:17 UTC

5

Downloading images from numerous URLs

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.

21 Comments
2024/11/16
13:18 UTC

18

Download all images from webpage

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")
}
13 Comments
2024/11/16
12:50 UTC

10

How can I use Powershell to write a .reg file?

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}"=-
22 Comments
2024/11/16
02:13 UTC

4

Using SharePoint via Intune

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.

10 Comments
2024/11/15
23:26 UTC

0

Powershell vscode Error Check doesnt work

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

10 Comments
2024/11/15
23:16 UTC

0

PS Script using <[Win32.Wallpaper]::SetWallpaper($imgPath)> will not work through Task Scheduler

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 :)

12 Comments
2024/11/15
21:55 UTC

5

is it possible to disable the interactive 'supply values for the following parameter'?

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

4 Comments
2024/11/15
18:40 UTC

30

Explanation with comma before Array ,@()

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 :)

26 Comments
2024/11/15
18:10 UTC

6

Need to find Edge Startup page settings in GPOs

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

13 Comments
2024/11/15
16:02 UTC

7

Powershell and Opentelemetry / Observability

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.

2 Comments
2024/11/15
14:52 UTC

7

Intune Warranty Info

This script queries Graph to get a list of all your devices in Intune, then queries Lenovo's site using SystandDeploy's Lenovo Warranty Script. Since Dell and (I think) HP requires paid API keys It uses Selenium to query their sites for the relevant warranty info.

 

Script can be found here. GitHub: Intune Warranty Info

 

Example of the Header output in the CSV.

ManufacturerUsernameEmailSerialNumberModelStatusIsActiveStartDateEndDate
13 Comments
2024/11/15
13:58 UTC

13

Powershell Interview

I have my interview for Cloud Administrator Role in next 7 days. They asked me to prepare Powershell for Interview. How can I prepare most out of Powershell? Any Suggestion would be really helpful.

31 Comments
2024/11/15
01:54 UTC

7

Why does this method cause an error: 0xC0000374 (STATUS_HEAP_CORRUPTION) ?

Why does this method cause an error 0xC0000374 (STATUS_HEAP_CORRUPTION) after most of the calls, even if it completes its task correctly?
If the question I am asking is stupid or obvious, please be understanding - I don't have much experience with this type of programmin

https://pastebin.com/WGdEgwqL

4 Comments
2024/11/15
00:16 UTC

5

Trouble with using special characters when updating user data in AD

A coworker was given a CSV with the profile information for a large set of employee profile data that needs updating.

He applied the changes using a script we'd written a couple of years ago and has worked flawlessly since. Until today, when we noticed that it was not adding the special characters found in many of the City, and Street Address' fields, but showed instead the magical � character when you look at them in AD.

So now, we have Montr�al, instead of Montréal

If I copy / paste the data into the accounts using Active Directory Users and Computers its fine, but is unsustainable due to the number of changes we need to make.

Sa far I've tried the following;

- Adding -Encoding UTF8 to the Import-CSV command

- Tried replacing the UniCode character with the UTF8 character with

 function UniReplace($n){  # Replaces Unicode Characters with UTF8
    [char][int]"0x$n"
}

...
          $addr = $addr -Replace 'è',"$(Unireplace E8)"
            $addr = $addr -Replace 'é',"$(Unireplace E9)"
            $addr = $addr -Replace 'ê',"$(Unireplace EA)"

            $city = $City -Replace 'è',"$(Unireplace E8)"
            $city = $City -Replace 'é',"$(Unireplace E9)"
            $city = $City -Replace 'ê',"$(Unireplace EA)"

- Tried changing the Encoding on the shell using

$defEncoding = [Console]::OutputEncoding
...
$OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new()
...
[Console]::OutputEncoding = $defEncoding

- Tried converting the string using;

$enc = [System.Text.Encoding]::UTF8
...

$city = $enc.GetBytes($city)
$addr = $enc.GetBytes($addr)

I've even gone so far as copied the good values from AD to the CSV, and the same results

2 Comments
2024/11/14
17:09 UTC

3

Connect to Azure and Power BI with a single login

I need to connect to our environment using connect-azaccount (Azure) and connect-powerbiserviceaccount (Power BI), with the same account. Is there a way to avoid having to log in twice? Note that MFA is required, so I can't just pass credentials.

3 Comments
2024/11/14
16:51 UTC

Back To Top