Skip Navigation

Search

Looking for feedback on my script

Script is made to control Veeam VBR Thanks for taking a look at my massive feature creep ;)

```powershell <# .SYNOPSIS Startet ein Veeam VBR Job

.DESCRIPTION Startet einen VBR Job basierend auf den Namen. Ursprünglicher Zweck war ein Verknüpfung von Jobs (z.B. als Pre-Execution Skript)

.PARAMETER JobName Job-Name des Backup Jobs

.PARAMETER JobType Typ des Backup Jobs Erlaubte Typen: VAW, VAL, VMware, Nicht erlaubte: Typen: HyperV, PVE

$Get-VBRBackup | Select-Object -Property Name,TypeToString,JobType Backup Pretty Verbose Typ im Skript Notizen ######################################################################################################## Backup Copy Job Backup Copy SimpleBackupCopyPolicy / / VAW Managed SRV Windows Agent Backup EpAgentBackup VAW CMDlet deprecated for Agent backups VAW Managed PC Windows Agent Policy EpAgentPolicy VAW CMDlet deprecated for Agent backups VAL Managed SRV Linux Agent Backup EpAgentBackup VAL CMDlet deprecated for Agent backups VAL Managed PC Linux Agent Policy EpAgentPolicy VAL CMDlet (probably) deprecated for Agent backups # UNGETESTET WERTE! Proxmox VE Proxmox Backup VmbApiPolicyTempJob PVE Nicht nutzbar mit Powershell via Start-VBRJob VMware VMware Backup Backup Backup VMware Hyper-V

.EXAMPLE Start-VeeamJob.ps1 -JobName passes F1234567-1abc-1234-ab1c-1a2345b6c78d to $JobName

.NOTES Author : Appoxo Version : 2.0

.LINK Job-ID auslesen: Get-VBRComputerBackupJob | Where-Object Name -CLike "Name" | Select-Object -Property Id, Name #>

[CmdletBinding()] Param( [Parameter(Mandatory = $true, HelpMessage = "Enter Job-Name of the VBR-Job")] [String] $JobName,

[Parameter(Mandatory = $true, HelpMessage = "Art des VBR-Jobs. Die Bezichnung ist NICHT canse-sensitiv!")] [string] $JobType )

Begin { Write-Host "Script started successfully" $ExitCode = 0

#TimeStamp Logging: function Get-TimeStamp {return "{0:yy/MM/dd} {0:HH:mm:ss}" -f (Get-Date)}

<# #Debug Values: $JobName = "L1 Backup Appoxo-PC2 (Games)" $JobType = "VAW" #>

# Variablen $workingDir = "C:\Skripte\SkriptLogs" $log = "$($workingDir)\Log-StartVeeamJob.log" $JobDetails = Get-VBRBackup | Where-Object Name -EQ "$($JobName)" $timeout = 9

# Vorbereitung if ($JobType -in @("VAW","VAL","VMware")){ Write-Host "Valid backup type selected" $JobTypUnbestimmt = 0 } else { Write-Host "Invalid backup type selected. Please choose something else :)" $ExitCode = 1 exit $ExitCode }

if (Test-Path -Path $workingDir) { } else { New-Item -ItemType Directory -Path "$workingDir" }

if (-not (Test-Path -Path $log -PathType Leaf)) { New-Item -ItemType file -Path $log Add-Content -Path $log "Log zur Überprüfung der Start von VBR-Jobs" } }

Process { Write-Host "You passed the following information:" $data = @([PSCustomObject]@{"Job Details"="$($JobDetails.Name)"; "Selected Job Type"="$($JobType)"}) $data | Format-Table -AutoSize Write-Host "The following Job-ID was found for this job: $($JobDetails.JobId)"

Write-Host "If there is an error please abort NOW." while ($timeout -gt 0) { Write-Host -NoNewline "`rThe script starts in $($timeout)" Start-Sleep -Seconds 1 $timeout-- } Write-Host "Starting script now!" Write-Output "$(Get-TimeStamp) Start des Backup Job Skripts. Für den Job '$($JobDetails.Name)' wurde die Job-ID $($JobDetails.JobId) gefunden!" | Add-Content -Path $log

try{ $startTime = Get-Date Write-Host "Validating input... This may take a while" if((($JobType -in @("VAW","VAL"))) -AND (($JobDetails.JobType -in @("EpAgentBackup","EpAgentPolicy")))) { Write-Host "Valid backup type '$($JobDetails.TypeToString)' was found. Starting now!" Start-VBRComputerBackupJob -Job $JobName | Select-Object -OutVariable JobResult } elseif (($JobType -in @("VMware")) -AND (($JobDetails.JobType -in @("Backup")))) { Write-Host "Valid backup type '$($JobDetails.TypeToString)' was found. Starting now!" Start-VBRJob -Job $JobName | Select-Object -OutVariable JobResult } elseif (($JobType -in @("PVE")) -AND (($JobDetails.JobType -in @("VmbApiPolicyTempJob")))) { Write-Host "Der Job des Typs $JobType ist aktuell nicht implementiert" $ExitCode = 1 exit $ExitCode <# Write-Host "Valid backup type '$($JobDetails.TypeToString)' was found. Starting now!" Start-VBRJob -Job $JobName | Select-Object -OutVariable JobResult #> } else { Write-Host "Invalid backup type '$($JobDetails.TypeToString)' was found. Please restart the script!" Write-Output "$(Get-TimeStamp) Bestimmung des Typs für den Job '$($JobDetails.Name)' nicht erfolgreich. Angegeben wurde '$($JobType)'" | Add-Content -Path $log $ExitCode = 1 $JobTypUnbestimmt = 1 }

# Job Result report if(($JobTypUnbestimmt -EQ 0) -AND ($JobResult.State -EQ "Stopped") -AND ($JobResult.Result -EQ "Success")){ Write-Host "Execution of the Job '$($JobName) was successful" Write-Output "$(Get-TimeStamp) Backup Job $($JobDetails.Name) erfolgreich ausgeführt" | Add-Content -Path $log $ExitCode = 0 } else{ Write-Host "Execution of the Job '$($JobName) encountered an error. Please check the VBR-Console" Write-Output "$(Get-TimeStamp) Fehler beim ausführen vom Backup Job '$($JobDetails.Name)'" | Add-Content -Path $log $ExitCode = 1 } #Stats $endTime = Get-Date $executionTime = $endTime - $startTime } catch { Write-Host "Something went wrong during execution" Write-Host $_ # This prints the actual error Write-Output "$(Get-TimeStamp) Error: $($_)" | Add-Content -Path $log $ExitCode = 1 } }

End { Write-Output "$(Get-TimeStamp) Skript abgeschlossen für $($JobDetails.Name) Job-ID $($JobDetails.Id)" | Add-Content -Path $log Write-Host "Script ended." $seconds = "{0:N2}" -f $executionTime.TotalSeconds $minutes = "{0:N2}" -f ($executionTime.TotalSeconds / 60) Write-Host "Time for stats! The script took $($seconds) seconds or $($minutes) minutes)" exit $ExitCode } ```

2

PowerShell Weekly for November 1, 2024

Announcements!

Blogs, Articles, and Posts

  • GitHub Copilot in Windows Terminal \ GitHub Copilot users can now use the power of GitHub Copilot to get command suggestions and explanations without leaving the terminal with Terminal Chat in Windows Terminal Canary 🚀 This is available for all GitHub Copilot Individual, Business, and Enterprise customers. To get started, sign up for a GitHub Copilot free trial and check out […]
  • Creating an AWS SSL Certs from Scratch (CLI and PowerShell) \ Learn how to create SSL certificates in AWS Certificate Manager using the AWS CLI. This tutorial walks through setting up permissions, requesting a certificate, and verifying its creation.
  • Export Complex PowerShell Objects to CliXML: A Practical Guide \ Learn how to export complex, nested PowerShell objects to CliXML while preserving their structure and relationships. Follow along with a real-world example using workout program data.
  • Dell Command Update – Install & Manage via PowerShell \ So if you haven’t read my last post yet, Dell Command Update – pulling back the curtains – GARYTOWN ConfigMgr Blog, you should, as I go into how Dell Command Update (DCU) gets it’s feed of information under the hood. That is the basis for a lot of things I’ll be doing. In this post, ... Read more
  • Popping Toast Notifications in PowerShell Core \ If you’ve ever popped a toast notification in PowerShell using the Windows Runtime (WinRT), you’ve probably discovered that, whilst it works fine in PowerShell 5, it doesn’t work at all in PowerShell Core (5/6/7+). That’s because the WinRT assemblies are not included in PowerShell Core – WinRT is an exclusively Windows thing
  • Powershell - Managing disks, partitions and volumes \ How to manage disks, partitions and volumes in Powershell
  • How to bypass Microsoft Graph PowerShell access restrictions \ Learn how to bypass Microsoft Graph PowerShell access restrictions and gain full directory access using PowerShell.

Projects, Scripts, and Modules

  • Show-PSRunObject: function to inspect objects \ Example function to inspect objects interactively. It shows what methods and properties the passed object has. You can go down/up the object hierarchy with key presses.
  • WinPostInstall \ Windows Post Install script written in PowerShell
  • PSBluesky \ If you are a Bluesky user, I'm working on a PowerShell module so that you can do things like post from a PowerShell prompt. Not ready to publish to the PSGallery, but the module is stable enough for you to kick the tires.
  • PSAPIClient v 1.1.0 \ This Powershell module is a wrapper for the use of one or more API(s). Each API can be configured and addressed independently. This allows easy use of multiple APIs within a session.

Books, Media, and Learning Resources

  • Learning PowerShell using Microsoft Learn \ This week, I posted a link to the PowerShell courses/learning paths on Microsoft Learn for PowerShell; I did that because there is so much material to learn from and use as a reference/help system. In this blog post, I will show you your options at Microsoft Learn to improve your PowerShell skills.

Community

Fun

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for October 25, 2024

Blogs, Articles, and Posts

  • Automating VM Deployment in Azure with PowerShell \ Learn how to automate the deployment of a Windows VM on Azure using PowerShell. This guide covers network setup, NSG rules, and IIS installation.
  • Get Active Directory ports with PowerShell \ Active Directory services communicate over specific ports needed for authentication, replication, and other directory services. Knowing these ports is crucial for configuring firewalls, ensuring secure communication, and troubleshooting network issues related to Active Directory services. This post will teach you how to get the Active Directory ports with PowerShell.
  • How to Set Directory Synchronization Features with the Graph \ Directory synchronization features control how the Entra Connect tool works when synchronizing accounts from Active Directory to Entra ID. The current advice is to use a cmdlet from the depreciated MSOL module to update settings. This article explains how to do the job with the Graph APIs, including cmdlets from the Entra PowerShell module.
  • Automating Sign-In Analysis with PowerShell and Microsoft Graph \ In this article, we'll walk through how to explore and analyze Conditional Access data in Microsoft Entra using the Developer Tools in your browser. The purpose of this walkthrough is to demonstrate how you can identify and extract the necessary Microsoft Graph API calls directly from the Entra portal, providing a foundation for automating this process with PowerShell.
  • List all EEEU and Anonymous links for SharePoint and OneDrive! \ A colleague of mine asked me before the weekend if I knew if there was a way to list all Everyone Except External Users and Anonymous links for OneDrive for Business. He had written a PowerShell script but had some errors.
  • Practical PowerShell: The Dark Power of Dynamic Parameters \ In this episode of Practical PowerShell, we dive into the dark power of dynamic parameters, and how to use them within in functions and scripts.

Projects, Scripts, and Modules

Community

  • Cross-Platform PowerShell and Sending Emails with Frank Lesniak & Neha Patil \ In this episode of the PowerShell Podcast, we dive into the world of cross-platform PowerShell with Frank Lesniak, who shares insights from his recent talk at PowerShell Saturday NC. Frank explores some unique use cases for PowerShell across different platforms and opens up about his interests beyond the scripting language.
  • BlueSky PowerShell Community starter pack \ If you're part of the exodus from X to Bluesky and you like PowerShell and automation, check out this PowerShell Community starter pack.

Events

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for October 18, 2024

Blogs, Articles, and Posts

  • Convert to Azure Premium SSD v2 Disks with PowerShell \ Azure Premium SSD v2 disks, currently in public preview, provide enhanced throughput and IOPS at a lower cost than earlier versions. You can convert existing disks to Premium SSD v2 using PowerShell. However, it's crucial to understand the specific limitations and requirements beforehand.
  • Manage Your SharePoint Online Environment with PnP PowerShell \ In this article, we explain how to get started using PnP PowerShell, and review some practical examples of where the module can immediately add value for tenant administrators.
  • Duplicate Drivers from a ConfigMgr Boot Image \ When creating new boot images in ConfigMgr, you often want to copy drivers from an older boot image. If you have many drivers added, it's way quicker to do that in PowerShell compared to comparing drivers in the boot image drivers tab.
  • Query WinGet software installer data with PowerShell \ I'm a big fan of WinGet, and the software available in their ecosystem is growing daily. Still, I'm always curious about what WinGet will download and how it does the silent install of the specified software. In this blog post, I will show you an easy way of retrieving that data :)
  • Automating Performance Monitor in Windows \ For advanced scenarios where you need to automate running Perfmon at scale
  • Type less by using PowerShell type accelerators \ I had heard the PowerShell term “type accelerators” a few times, but never really knew what that meant. I finally decided to check out the about_Type_Accelerators docs and it turns out they’re simply aliases for .NET types.

Projects, Scripts, and Modules

Books, Media, and Learning Resources

Community

  • Exploring Redfish Protocol, Data Science, and PowerShell with Blake Cherry & Danny Stutz \ In this episode of the PowerShell Podcast, I sit down with Blake Cherry to discuss the Redfish Protocol and its impact on simplifying data center hardware management, drawing insights from his talk at PowerShell Saturday, NC. We explore how Redfish is reshaping IT systems at scale. I also speak with Danny Stutz, who dives into the intersection of PowerShell and Data Science, covering topics like AI, data analysis, and K-means clustering, all applied to real-world use cases using PowerShell. Whether you're managing hardware or looking to integrate advanced data science techniques into your scripts, this episode has something for everyone!
  • OpenAI for PowerShell with Doug Finke \ You should be writing tests for your PowerShell scripts... but how to get started? Doug talks to RunAsRadio about using ChatGPT and GitHub Copilot to explore different aspects of PowerShell, including testing!

Events

  • PowerShell AI Build Hour - Doug Finke \ Friday, October 25, 2024 at 12:30 PM EDT - Ready to go from zero to app hero? I'll live demo building an app using the new OpenAI Canvas—the interface that transforms writing and coding into an interactive adventure. This isn't just chat; it's creating real-world projects, start to finish.

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for October 11, 2024

Blogs, Articles, and Posts

Books, Media, and Learning Resources

Community

  • Culinary to Command Line: Catching Up with Drew McClellan \ In this episode of the PowerShell Podcast, we welcome back the "bestsest in the midwestest" Drew McClellan, who shares his recent promotion from Jr. Sysadmin to SysAdmin II. Drew talks about how he uses PowerShell in his daily role, tackling new software implementations and projects, and his approach to continuous learning. We also dive into how the OnRamp experience at PowerShell Summit helped prepare him. As a bonus, Drew, a chef for 10 years, dishes out some recipe recommendations to Andrew!
  • Shorten The Code - Results and Learnings with Well-known Community Members \ Xavier Clinquart from the Belgian PowerShell User Group has analyzed all scripts, and now it is time to take a look at the best ones. Together with well-known members of the PowerShell community, we will talk about the results and learnings of this fun competition.

Fun

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for October 4, 2024

Blogs, Articles, and Posts

  • Restore classic context menu in Windows 11 Explorer using Group Policy or PowerShell \ Alongside the revamped Start Menu, one of the most noticeable changes in Windows 11 is the redesigned context menu in File Explorer. However, these modifications are not merely aesthetic – they also restrict its functionality. You can deploy a registry key using Group Policy Preferences to restore the classic context.
  • How to Create Azure Service Principals in PowerShell \ Learn how to create Azure service principals using PowerShell, enabling secure automation for managing Azure resources like virtual machines.
  • Microsoft Retires the Revoke-SPOUserSession Cmdlet \ Unsurprisingly, Microsoft announced the deprecation of the Revoke-SPOUserSession cmdlet for November 2024. The cmdlet is replaced by the Revoke-MgUserSignInSession cmdlet, which works across Microsoft 365 rather than just SharePoint Online. All of this happened while the 2nd annual PowerShell Script-Off happened at TEC 2024 and competitors struggled with what to do to secure a user account for an ex-employee.
  • GitHub Copilot Password Warning \ Did you know that GitHub Copilot is now sensing hard coded credentials and giving you a warning? It’s not perfect, but even if something looks like hard coded creds it will flag it, as on another script I had, it contained numbers that looked like they could be private, and it gave me a warning
  • Using Get-Content in PowerShell \ I use Get-Content a lot (or cat, gc, and type as its alias) to display or track the contents of a file. There are different parameters for it, and in this blog post, I will show you what you can do with those :)
  • Customize your Windows 11 (23H2 and onwards) taskbar during OSD with ConfigMgr using just PowerShell \ Approximately two years ago, I authored a blog post detailing how to customize the taskbar in Windows 11.
  • Running PSScriptAnalyzer in GitHub Actions \ I was working on a project recently that has some PowerShell scripts and I wanted to add some kind of linting for PRs, as you do. The go-to for PowerShell seems to be PSScriptAnalyzer and it's something I've already setup in VS Code. Great! The next step was to setup
  • PowerShell Potluck - September 2024 \ Welcome back to another PowerShell Potluck, and you didn't have to bring a thing, other than a little curiosity and a willingness to try new things.

Projects, Scripts, and Modules

  • EntraFIDOFinder – New PowerShell Module \ After so much interest from my post on Friday, I figured I’d do one better and make a PowerShell module that does it for you. So now you will be able to find which FIDO2 keys are attestation compatible with Entra right from your terminal. In the very near future I will have individual functions

Books, Media, and Learning Resources

Community

  • PowerShell + DevOps Global Summit 2025: Call for Papers Now Open! \ PowerShell + DevOps Global Summit 2025: Call for Papers Now Open! Calling all innovators, problem-solvers, and thought leaders in the PowerShell and DevOps realm!
  • Spectre Console and TUI Magic with Shaun Lawrie \ On this episode of The PowerShell Podcast, we sit down with Shaun Lawrie to discuss terminal user interfaces (TUIs) and his work on the PWSHSpectreConsole project. Shaun shares insights into the world of TUIs, offers valuable career advice, and talks about his journey in tech. Tune in for practical tips and an in-depth look at what it takes to thrive in the PowerShell ecosystem.

Fun

  • PowerShell ASCII Art \ I posted my Windows Terminal this week on social media channels, including LinkedIn, and received some responses about the login banner screen. In this blog post, I will show you an easy way to pimp your PowerShell Console ;)

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for September 27, 2024

Blogs, Articles, and Posts

  • Build dynamic JSON with PowerShell \ I recently did a Contacts Sync with GRAPH Api and PowerShell to create Contacts in a Shared Mailbox and USer Contact Folder. At this time, it was needed to build dynamic JSON related to existing Values, so I looked for some posts on how to build dynamic JSON with PowerShell.
  • How to install PowerShell 7 and essential tools on Linux \ As you prepare for the OnRamp track at the PowerShell + DevOps Global Summit, this guide walks you through installing the essential tools on your Ubuntu Linux system if that's your preferred operating system. You'll learn how to install PowerShell version 7, Visual Studio Code, and the PowerShell extension for VS Code to ensure your system is prepared for the event. If you're using Windows 11, refer to the companion article, How to install PowerShell 7 and essential tools on Windows 11. A future article covers installations on macOS.
  • Installing the Entire Microsoft Graph PowerShell SDK Seems Like the Right Idea \ An article described some benefits that could be gained from not installing the complete Microsoft Graph PowerShell SDK. The question is whether the claimed benefits are more theoretical than actual. It’s hard to say because it all depends on how someone uses the SDK for development or to run scripts. Anyway, it’s a topic worth discussing.
  • How to Authenticate to Azure Using PowerShell (User and Device Authentication) \ Learn how to authenticate to Azure using PowerShell, including module installation, interactive and device login methods, verifying sessions, and managing multiple subscriptions.
  • Passkey Provider AAGUIDs PowerShell Module \ The FIDO2 specification requires each security key vendor to provide an Authenticator Attestation GUID (AAGUID) during registration. An AAGUID is a 128-bit identifier indicating the key type, such as the make and model. Passkey providers on desktop and mobile devices are also expected to provide an AAGUID during registration.
  • PowerShell Confirm Parameter: Best Practices for Safe Scripting \ The PowerShell Confirm parameter is an essential safeguard that prompts users before performing potentially destructive actions. This article will explore how to implement the -Confirm parameter in custom PowerShell functions to make them more robust and user-friendly. What is the PowerShell Confirm parameter?
  • Outlook Email Mover \ The way I manage my email might seem a bit strange. Due to working in IT, I get lots of emails. Some emails need action, some are regular emails, and some are notifications I want to know about as soon as they happen. I feel like a normal person would make an Outlook rule to…
  • SQL Query Stats via Powershell \ Checking query runtimes via PowerShell

Projects, Scripts, and Modules

  • PowerShellRun \ Terminal Based Launcher and Fuzzy Finder for PowerShell.

Books, Media, and Learning Resources

Community

  • Innovating with PowerShell: Micah Shonyo’s Path to C# Mastery \ In this episode of the PowerShell Podcast, we sit down with Micah Shonyo to explore his inspiring journey into PowerShell, from his early days learning the language to his current projects. We dive into the story behind his Microsoft Cluster Management module, discussing what motivated him to create it and how it helps sysadmins. Micah also shares how learning PowerShell opened the door for him to start using C#, blending scripting with development to elevate his technical skills. We wrap up the conversation with insights into his career goals and aspirations for the future.
  • Inside IT Automation E16 \ The History of PowerShell with Jeffrey Snover

Fun

Events

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

1

PowerShell Weekly for September 20, 2024

Blogs, Articles, and Posts

  • Get-Mailbox Versus Get-ExoMailbox \ Microsoft's advice is to use the Get-ExoMailbox cmdlet instead of its older Get-Mailbox counterpart. Generally, this is good advice that you should follow. However, the older cmdlet can do a job in certain circumstances, so don’t write it off completely. More importantly, make sure that filtering of objects is done using server-side filters. This will improve script performance significantly.
  • Simple Tip for GitHub Copilot \ If you have GitHub Copilot, you may or may not know about this little tip, but wanted to let you know just in case. It has saved me so much time and it can be applied to a lot of scenarios.
  • Query the required permissions of a Microsoft Graph cmdlet \ Microsoft Graph can be difficult sometimes. There are loads of PowerShell Microsoft Graph Modules and cmdlets that require different permissions. In this blog post, I will show you how to query the permissions for a cmdlet, multiple cmdlets, or all cmdlets from a specific Microsoft Graph module.
  • Exploiting Exchange PowerShell After ProxyNotShell: Part 3 – DLL Loading Chain for RCE \ As you may know, I recently presented my Exchange-related talk during OffensiveCon 2024. This series of 4 blog posts is meant to supplement the talk and provide additional technical details. In this article, part 3 of the series, I describe a chain of 3 vulnerabilities that led to remote code exec
  • Attacking PowerShell CLIXML Deserialization \ In this article, we will learn that using PowerShell’s CLIXML deserialization could lead to undesired effects, including remote code execution. We will also see that widely used solutions, like PowerShell Remoting and PowerShell Direct (Hyper-V), rely on such deserialization and could make you vulnerable to this kind of attack.

Projects, Scripts, and Modules

  • Tabby \ Tabby (formerly Terminus) is a highly configurable terminal emulator, SSH and serial client for Windows 10, macOS and Linux

Books, Media, and Learning Resources

  • PowerShell Advanced Functions: Getting Started Guide \ Advanced functions take your PowerShell development to the next level, letting you create cmdlet-like scripts with advanced features. In this article, we’ll dive into what makes cmdlets and advanced functions essential in PowerShell, with examples and tips to help you master them. What is a cmdlet? A PowerShell cmdlet (pronounced “command-let”) performs a specific task
  • PnP PowerShell Changed!!! ACT NOW \ In this video, I will show you about a big change in the way PnP PowerShell will work going forward. You might be facing an issue right now when you are working with PnP PowerShell. Watch this video to know how you can resolve this and get going.
  • Harness AI to Analyze Your Workflow with Custom PowerShell Scripts \ In this video, Doug Finke, a 16-time Microsoft MVP, showcases his PowerShell function GetWhatIWorkedOn. This tool helps you effortlessly track and summarize the files you've worked on over any specified period. By scanning multiple directories, it lists all the files you've modified, giving you a clear picture of your recent activities.

Community

  • Building Modern PowerShell Solutions: Justin Grote on TUIs, .NET, and Module Magic \ In this episode, we chat with Justin Grote about his work with PwshSpectreConsole and the power of TUIs in PowerShell scripting. Justin takes us through his impressive collection of PowerShell modules—ModulePath, GallerySync, and ModuleFast—and how they enhance the PowerShell experience. We also explore the advantages of .NET's Common Language Runtime (CLR) in PowerShell, using Spectre.Console as a prime example. Finally, Justin shares his thoughts on transitioning from Windows PowerShell to PowerShell 7 and the performance and feature benefits that come with the upgrade.
  • Scriptember Live: "PowerShell Is Fun - Episode 2" with Microsoft MVP Harm Veenstra \ In this live stream, we'll talk about how to have fun with PowerShell while improving IT automation tasks and processes.

Fun

  • Friday the 13th PowerShell Fun \ Well here are once again and another Friday the 13th. I love these days because I feel challenged to come up with 13 PowerShell related tidbits which I hope you'll find fun and maybe even a little educational. Manage and Report Active Directory, Exchange and Microsoft 365 withManageEngine ADManager Plus - Download Free Trial Exclusive...

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for September 13, 2024

Blogs, Articles, and Posts

  • Recover data from corrupted BitLocker drives with repair-bde and key packages \ Activating BitLocker encryption on a drive automatically generates a 48-digit numeric recovery password. This password is crucial if other unlocking methods fail and Windows prompts you with the BitLocker recovery console during startup.
  • Practical Graph: Working with Microsoft Lists using the Microsoft Graph PowerShell SDK \ Microsoft Lists are a powerful tool for end users to store and manage data stored in SharePoint Online sites. The Microsoft Graph PowerShell SDK includes cmdlets to work with Microsoft Lists and this article explains how to use the cmdlets to add new lists, add items to lists, retrieve data from lists, and remove items from lists.
  • My PowerShell for Visual Studio Code extension settings \ I use Visual Studio Code to create and edit PowerShell scripts. The PowerShell Extension from Microsoft has some excellent features that will make your scripts more readable and consistent formatting-wise. In this blog post, I will show you my configuration and the options I use.
  • Register an Entra ID Application to Use with PnP PowerShell \ As the volume of threats increases rapidly, staying aligned with the recommended practices is essential to enhance security effectively. As part of this, the multi-tenant PnP Management Shell Entra ID app was deleted on September 9, 2024, to improve application security. This change now requires admins to register their own…
  • Semi-Dynamic Static PowerShell Function Definitions for a Dynamically Semi-Static World \ It’s been a while since I posted anything to my blog. I needed a break. But I needed a break from the break. I hope you don’t mind. This is admittedly an “edge case” scenario. The “need” (with air quotes) for this occurred within fairly uncommon set of circumstances, but I thought the methodology might be useful in other cases. Or maybe not. But if it’s of some help to you, that makes it worth the effort for me.
  • WSUS – Cleanup using Powershell with email notification output \ If you are using WSUS in your environment, you may want to run a scheduled task to cleanup old updates and compress some of the larger updates to free up space on your server. A good way of doing this is to run a Powershell script which will take care of all your cleanup requirements and as we are using Powershell, we can even get it to send us an email once it is complete with the output information on what the script has managed to clean up.

Projects, Scripts, and Modules

  • Microsoft 365 Licensing Report Script V1.94 \ The Microsoft 365 Licensing Report PowerShell script has been upgraded to generate detailed license information and to deal with expired license subscriptions. You can download V1.94 of the script from GitHub. Before attempting to run the licensing report script, take the time to read previous articles to understand the basics of the script and how to generate the files used for pricing information.

Books, Media, and Learning Resources

  • Turn PowerShell Into Your Excel Automation Machine \ Get ready to see how PowerShell can transform the way you work with Excel.
  • Azure Functions & PowerShell \ Join me as I discuss PowerShell-based Azure Functions. we will go through local Function development and testing to deploy a Function to Azure and even an Account storage queue-triggered Function that creates a Resource Group and Storage account from a queue message.

Community

Fun

  • Shorten the Code – Win cool Prizes \ Welcome to the ScriptRunner Shorten the Code Challenge! This exciting competition invites PowerShell enthusiasts to demonstrate their scripting prowess by transforming a PowerShell script into concise, efficient code.

Events

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for September 6, 2024

Announcements!

  • Scriptember 2024 \ A month-long celebration of PowerShell and its vibrant community

Blogs, Articles, and Posts

  • New in Windows Terminal: Restore buffers, code snippets, scratchpad and regex \ Windows Terminal unveiled a range of noteworthy features in versions 1.21 and 1.22 Preview, including the capacity to retrieve previous sessions' output buffer upon startup, store code snippets for reuse within the console, and utilize a scratchpad for crafting intricate commands.
  • PowerShell: Calculate the total size of Files \ In this post I will show how to use PowerShell to calculate the total size of all files. This will be a short post but maybe a very helpful one.
  • Transferring Reusable PowerShell Objects Between Microsoft 365 Tenants \ People often need to transfer objects or code between Microsoft 365 tenants. When it comes to dealing with objects, the Microsoft Graph PowerShell SDK's ToJsonString method is very useful. The method outputs a string containing JSON content, but only for object properties that have a value. This makes the much easier to use the output as the basis for a template object or as the payload body to create an object in another tenant.
  • Get List Item Count in SharePoint Online Using PowerShell \ In organizations, SharePoint lists are essential for organizing and managing various data, from tracking tasks to managing customer information and inventory. These lists not only streamline collaboration but also ensure that data is easily accessible and well-structured.
  • Practical PowerShell Series: Part 6 \ The practicalities of producing PowerShell output and generating logging are other essential scripting elements. No administrator likes to stare at a blank screen, wondering if the command just entered is functioning or not.
  • Configuring PowerShell settings using Intune or Group Policy \ Every Windows device has PowerShell installed by default. (Sadly, it's still only version 5, not version 7.) However, you want to configure the devices' security and log settings. In this blog post, I will show you how to do that using Microsoft Intune or Group Policy.
  • Taming My ADHD with Obsidian and PowerShell \ Alleviating my ADHD headaches with Obsidian. Periodic Notes and Templater extensions save the day by reminding me of the next step towards my larger goals.
  • 5 Reasons you should be using PSReadLine \ Get up to speed and use PSReadLine more often - in his first article for us, author Jeffery Hicks provides his 5 reasons why he recommends using PSReadLine.

Books, Media, and Learning Resources

  • Mastering Time in PowerShell: Measure statistical properties within time spans with PSDates [OC] \ Unlock the power of time manipulation in PowerShell with the Group-TimeSpan and Measure-TimeSpan cmdlets from the PSDates module! In this video, we'll dive deep into how you can group data by specific time spans and measure statistical properties like sum, average, maximum, and minimum within those groups. Whether you're looking to analyze logs, monitor system performance, or perform data analysis, these cmdlets offer powerful tools to streamline your workflows and enhance your data manipulation skills in PowerShell. Watch now to become a master of time-based data analysis!
  • Making Microservices with Docker and PowerShell \ The Pacific PowerShell User Group talks about making Microservices with Docker and PowerShell

Community

  • Being a Lazy Administrator with Bradley Wyatt \ In this episode of the PowerShell Podcast, I had the pleasure of chatting with Bradley Wyatt, also known as the Lazy Administrator. We explored his inspiring journey from college dropout to becoming a 5x Microsoft MVP and how he transformed his personal knowledge base into a globally recognized blog that serves as a vital resource for IT professionals. Bradley shares the lessons he’s learned along the way, his passion for automation, and the impact of his work on the PowerShell community.
  • Inside IT Automation - E11 \ Bruno Buyck: Learning PowerShell with Lego

Events

  • Scriptember Live Stream Episode 1 \ Scheduled for Sep 11, 2024. In this live stream, we'll talk about how to have fun with PowerShell while improving IT automation tasks and processes.

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PSDates v1.0.5 released with new data analysis functionality

I'm excited to announce the latest update to PSDates is live on the PowerShell Gallery and GitHub.

This version introduced two powerful new functions designed to enhance data analysis capabilities in PowerShell!

  • Group-TimeSpan: This new cmdlet allows you to easily group objects by a specified time intervals. Whether you're working with logs, transactions, or any time-based data, you can now quickly organize your data into meaningful time intervals. This makes it simpler to analyze patterns, trends, and performance over time.

  • Measure-TimeSpan: This cmdlet takes the Group-TimeSpan to the next level by measuring statistical properties such as sum, average, maximum, and more within grouped time spans. It's perfect for generating detailed reports, analyzing system performance, or monitoring trends within your datasets.

It's available for installation from the PowerShell Gallery Install-Module -Name PSDates

PSDates on GitHub

0

PowerShell Weekly for August 30, 2024

Announcements!

  • PnP PowerShell Changes Its Entra ID App \ On August 21, 2024, news emerged that the PnP PowerShell module will transition from using a multi-tenant Entra ID app to a tenant-specific app. The change is scheduled for September 9, 2024, which doesn’t leave a lot of time available for developers to review, update, and test PowerShell scripts based on PnP PowerShell. Some extra warning would have been nice.
  • Windows Terminal Preview 1.22 Release \ Hello friends, we have a new Windows Terminal Preview release! Windows Terminal Preview 1.22 is a large release that contains new features such as Sixel image support (a LARGE community contribution!), Grapheme Cluster Support, the Snippets Pane, Quick Fixes in CMD, and a new Cooked Read popup in CMD to name a few!
  • PowerShell 7.5.0 preview 4 released \ Download the newest preview release of PowerShell 7.5.0

Blogs, Articles, and Posts

  • Display Markdown files in PowerShell \ Creating Markdown files is something that I do regularly, usually in Visual Studio Code or Obsidian. But when working in a Windows Terminal or a standard PowerShell prompt, it's nice to display those .md files in those, too, with all the formatting that Markdown gives you. In this blog post, I will show you how :)
  • Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel \ TLDR make sure your system time is correct in Windows & BIOS Ok, this has been well documented around the internet, and the typical answer is: Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel – Stack Overflow However today I was really annoyed because that was already built into my script
  • How to make your Windows ssh keys available to git in WSL \ A neat little trick.

Projects, Scripts, and Modules

  • Mastering Active Directory Hygiene: Automating Stale Computer Cleanup with CleanupMonster \ Have you ever looked at your Active Directory and wondered, "Why do I still have computers listed that haven't been turned on since World Cup 2016?" Yeah, we've all been there. Keeping AD clean and up-to-date is like trying to organize your garage—it’s easy to put off until it becomes a total mess.
  • Creates a PSSession that targets a scheduled task process \ Created New-ScheduledTaskSession for PowerShell that can create a PSSession for use with Invoke-Command to run PowerShell code in the context of a scheduled task process. This is a fun way to bypass NETWORK logon limitations like the Windows Update API
  • PowerShell Nerd Fonts Installer \ I recently had the chance to work on a PowerShell installer for Nerd Fonts, which includes the new Cascadia Code/Mono from the Microsoft repository.

Books, Media, and Learning Resources

  • The Best PowerShell Cheat Sheet \ Looking for a good PowerShell cheat sheet? Then you are in the right place. I have been working with PowerShell for the last 10 years. During that time I have written down the most useful cmdlets, operators, or useful commands in many places, just to remind them.
  • Everything you wanted to know about exceptions \ Error handling is just part of life when it comes to writing code.

Community

  • Be the Community: Insights and Event Log Automation with Phil Bossman \ In this episode of the PowerShell Podcast, we sit down with the newly minted Microsoft MVP, Phil Bossman, to dive into the heart of the PowerShell community and what it truly means to "be the community." We discuss the excitement building around PowerShell Saturday NC and the invaluable learning opportunities it offers. Phil shares his expertise on exploring event logs and how to harness their power for PowerShell automation, providing practical insights for both beginners and seasoned pros. Join us as we celebrate Phil's journey to becoming an MVP and gain inspiration from his dedication to the PowerShell community.
  • Inside IT Automation E10 \ Guy Leech talks about his PowerShell journey, the use of AI and more.

Fun

  • Among Us \ Randomly decided to add an Among Us theme to the end of the script to tell me it's finished running :)

Events

  • Scriptember Kick-Off: Let's celebrate PowerShell! \ We are kicking off a month-long celebration of PowerShell and its vibrant community. Join our kick-off session where we talk with some awesome members of the PowerShell community. We will discuss why PowerShell is a great IT automation technology, how to learn it and how PowerShell helps IT professionals advancing their careers.

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for August 23, 2024

Announcements!

Blogs, Articles, and Posts

  • PDF Text to SQL Data: Using OpenAI's Structured Output with PSOpenAI \ Incredible! I just used PowerShell and OpenAI to import text from a PDF right into SQL Server 🚀 AI's usefulness is often debated but this is such a great use-case. I also see it being useful for automatically adding SharePoint document metadata and cleaning dirty data.
  • Unlock inline PowerShell capabilities to streamline Logic Apps workflows \ The new inline PowerShell action, now in preview, adds flexibility to Logic Apps by enabling users to embed PowerShell scripts directly into workflows. This feature unlocks new possibilities for complex integrations, and I'm excited to demonstrate its potential with a bank reconciliation workflow demo.
  • Find paired Azure region locations with Azure PowerShell \ In this article, you learn how to add a custom property to the Azure PowerShell Get-AzLocation cmdlet output to display the physical location for paired regions in Azure. This information isn't available by default but can help you understand the resiliency and redundancy of your Azure resources like geo-redundant storage (GRS) and other Azure services that rely on Azure Storage for replication.
  • Send email notifications about expiring Active Directory passwords with a PowerShell script \ Enforcing a policy for regular password changes is no longer recommended, as it can result in more helpdesk requests due to expired passwords, especially for VPN users, and may actually undermine security. However, timely notifications can help mitigate issues when password changes are necessary. Learn how to notify users with Group Policy or a PowerShell script.
  • Sort your local photos with Azure OpenAI and PowerShell! \ Quick short blogpost here today. I have created a PowerShell script that reads your local photos, uses Azure OpenAI to get the type/category they belong to and move them to a folder with that name. To accomplish this I am using the Azure OpenAI GPT4-o model. You can read here how you set up an … Continue reading Sort your local photos with Azure OpenAI and PowerShell!
  • PowerShell RegEx: Getting Started Guide \ PowerShell stands out as a versatile tool in scripting and automation, offering a wide array of functionalities to manage systems and process data. One PowerShell feature is the ability to use Regular Expressions (RegEx), a method for searching, matching, and manipulating strings based on specific patterns.
  • Custom Script Setting in SharePoint & OneDrive Removed \ Last week, we published a blog discussing Microsoft retiring SharePoint Add-Ins. In that blog, we briefly discussed how the Classic Mode for Custom Scripts has been affected by that change. The Custom Script setting in SharePoint and OneDrive has already been removed – the change took place in May 2024.   There is a new PowerShell command (DelayDenyAddAndCustomizePagesEnforcement) that will allow administrators to delay any changes until November of this year. Additionally, the NoScriptSite setting will be configured to True for all existing sites except for specific site templates.   How Will The Removal of Custom Script Settings Affect My Organization?
  • My first experience trying to use the PowerShell beta module for Microsoft 365 Backup \ I use Microsoft 365 Backup for my tenant; it's a simple way to back up Exchange, OneDrive, and SharePoint data to an Azure Subscription. There was no PowerShell module to query and configure things, but that has changed because the Beta module was released three days ago. In this blog post, I will describe my first experience trying to use the new module.
  • A PowerShell function to easily retry any code \ Performing retries to make your code more resilient is a common pattern. By leveraging a PowerShell ScriptBlock, we can create a function to avoid constantly rewriting the same retry logic again and again.

...continued in comments

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

3

PowerShell Weekly for August 16, 2024

Blogs, Articles, and Posts

  • Unlock BitLocker drive from Windows PE with a PowerSell script \ BitLocker can pose a significant challenge when multiple PCs need to be booted from an external drive for troubleshooting. The helpdesk must manually enter the 48-digit recovery password each time. However, this process can be automated by exporting the keys and using a script.
  • Handling the Too Many Retries Error and Dealing with Odd Numbers of Audit Events \ The AuditLog Query Graph API remains in beta status but cmdlets are now available in the Microsoft Graph PowerShell SDK. This led to some oddities in results when the number of audit events found by a search didn't match those reported by the Purview compliance portal. It all worked out in the end. In other news, the Set-MgRequestContext helped sort out some retry problems.
  • Using Export-Clixml and Import-Clixml for credentials in PowerShell scripts \ Using clear-text passwords in PowerShell scripts is, of course, a bad thing to do. But sometimes, you need to use credentials in a script to connect to a server, service, etc. In this blog post, I will show you how you can use Export/Import-Clixml to do that.
  • 10 Useful Tips for Customizing SharePoint List Fields with PnP PowerShell \ Recently, I was working on building a Power Apps application that takes data sources as a SharePoint list. To avoid creating SharePoint lists and manually adding different types of columns, I wrote a PowerShell script. While adding different types of columns to the SharePoint lists
  • Confirm Domain Join during OSD \ I’ve got a small group in my TS that double checks the domain join status, then exit with an error code if the OSD process didn’t join the domain properly. Basically, I’m using PowerShell to do a couple of lookups and writing the information to variables, which I then use to trigger an exit command.
  • Get Microsoft 365 Users’ Registered MFA Methods With PowerShell \ Nowadays, security is paramount and multifactor authentication (MFA) stands as a critical line of defense in protecting sensitive information within Microsoft 365 environments. As organizations increasingly adopt to configure MFA, it becomes essential for administrators to monitor the authentication methods registered by users.

Projects, Scripts, and Modules

  • Introducing PSReminderLite \ For several years, I have been using a PowerShell module I wrote called MyTickle to help me manage my reminders and events. I spend my days at a PowerShell prompt, and I wanted an easy way to keep track of upcoming events.
  • Updated Media Tool available \ Back in 2023, I posted a Media Tool app (which uses PowerShell behind the scenes) to download Windows 10 or 11 media, for both x64 and ARM64 architectures.

Books, Media, and Learning Resources

  • How I got my Windows PowerShell Terminal looking better \ This video starts with a Windows 11 23H2 installation with the default Windows PowerShell Terminal. I'm a bit of a fan of Oh-My-ZSH + PowerLevel10k for the Linux Desktops I built for work, so my goal was to have a similar looking prompt on Windows for my PowerShell terminal. I take you step by step through the process of improving the appearance of the terminal.
  • How to get info from your vCenter \ Hey everyone! In this video, I'm diving into a game-changing PowerShell one-liner that completely simplifies how I gather vCenter information. If you've ever been frustrated by manual scripts that take too much time and effort, this is the solution you've been waiting for!

Community

  • TechMentor Highlights: Greg Altman, Mike Nelson, and James Petty Share PowerShell Wisdom \ In the latest episode of the PowerShell Podcast, we had the pleasure of interviewing Greg Altman, Mike Nelson, and James Petty. We spoke with three speakers at TechMentor in Redmond, including a special birthday guest. We covered topics such as imposter syndrome, details on the guests' talks, recommended books for starting and advancing in PowerShell, and a healthy helping of laughs throughout. Tune in for insightful conversations, valuable insights, and a few chuckles along the way!
  • Inside IT Automation l E08 l Steve Lee talks about PowerShell 7, AI, Project Mercury, DSC and more \ In this "Inside IT Automation" episode Heiko has a conversation with Steve Lee at the PSConfEU in Antwerp. They talk about the PowerShell 7, AI, Project Mercury PowerShell DSC and more. He also gives some insights into how the Microsoft PowerShell team works.

Events

  • Build a Superfast Research Assistant using PowerShell and AI \ Join me for a hands-on session where we will build a superfast research assistant using PowerShell and AI. This powerful tool leverages the latest OpenAI models using my PowerShell module PSAI to search the web, gather information, and generate comprehensive research reports in seconds.
  • Coding Rock-Solid AI Agents: PowerShell Precision \ In this session, you'll learn how to harness the PSAI PowerShell module and the newly developed PSAIAgent to create AI agents with memory, contextual knowledge, and tool integration. We’ll dive into practical steps for building these advanced agents, ensuring each one is reliable, robust, and ready for real-world application.

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for August 9, 2024

Blogs, Articles, and Posts

  • PowerShell: When to use Add-Type and New-Object ? \ In this blog post, I will discuss when you need to add classes with Add-Type and when you can provide classes with New-Object. I would say, let’s get started.
  • Managing DHCP Leases and Reservations with PowerShell \ In this tutorial, we'll explore how to manage DHCP leases and reservations using PowerShell. Effective lease and reservation management is crucial for maintaining a smooth-running network, preventing IP address conflicts, and ensuring that critical devices always receive the same IP address.
  • Windows device provisioning with Workspace ONE, part 2: Apps and policies \ In the first part, I got to the point where I could successfully get a device into a managed state, but that doesn’t mean the device is actually usable.
  • PowerShell: A Microsoft 365 Admin Roles Membership Report \ Manually reviewing the membership roster for each of the dozens of RBAC roles in a Microsft 365 tenant is quite
  • Creating a development Windows Sandbox using PowerShell and WinGet \ As I mentioned before, I like Windows Sandbox! However, since Windows 11 24H2, Windows Sandbox has been missing two things I often use: Notepad and Windows ISE. In this blog post, I will show you how to start Windows Sandbox and automatically install your preferred editors and tools using WinGet and PowerShell.
  • Understanding Get-EXORecipient \ This guide will provide you with the knowledge and tools you need to effectively manage your Office 365 mailbox using the Get-EXORecipient. Understanding Exchange Recipient Type Details When managing an Exchange environment, understanding the different types of recipients is crucial for effective administration. Exchange Online supports a variety of recipient types, each serving different purposes...

Projects, Scripts, and Modules

  • Azure AD Incident Response PowerShell Module \ The Azure Active Directory Incident Response PowerShell module provides a number of tools, developed by the Azure Active Directory Product Group in conjunction with the Microsoft Detection and Response Team (DART), to assist in compromise response.

Books, Media, and Learning Resources

  • Inside IT Automation l E07 \ Xavier Clinquart talks about PowerShell, the PoSh community and more.
  • Build a PowerShell Menu in 5 minutes \ In this video, we break down the concept of switch statements and how they can be utilized to create an interactive menu for users. We'll start with the basics of setting up a script, defining functions, and understanding how to handle user inputs in PowerShell.

Community

  • Exploring Cybersecurity with PowerShell and John Hammond \ In this episode of the PowerShell Podcast, we sit down with renowned security researcher John Hammond. Recorded in person in Utah, we delve into John's unique insights on PowerShell and its role in cybersecurity. John shares his experiences with PowerShell attacks, discussing how it’s used in various malware and the importance of implementing security features like constrained language mode and script block logging. He highlights practical tips for making PowerShell environments more secure and emphasizes the need for continuous learning and experimenting within safe environments. We also explore how to transition into security-focused roles, with John providing valuable advice for those looking to combine their PowerShell skills with a career in cybersecurity.

Fun

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for August 2, 2024

Blogs, Articles, and Posts

  • The Maddening Side of the Microsoft Graph PowerShell SDK \ All software has unique quirks, and the foibles of the Microsoft Graph PowerShell SDK are well known. But it’s much harder when the underlying foundation contributes to the craziness as described in this article. Graph pagination works in a specific way and Microsoft tunes the Graph to deliver great performance by reducing the set of properties returned for objects. Both can cause concern for developers.
  • Microsoft Entra PowerShell module, successor to the Azure AD PowerShell module \ The Microsoft Entra PowerShell module is the successor to the Azure AD PowerShell module. It's designed to streamline management and automation for the Microsoft Entra product family, which includes the services formerly known as Azure Active Directory.
  • Using Switch in PowerShell \ Everyone uses If statements in their scripts: If this, then that. Or If not this, then that, multiple If, and even Elseif. But there is another option, Switch. In this blog post, I will show you how you can use Switch and make your scripts more readable in the process :)
  • Reading, Rotating, and Reporting on LAPS and BitLocker in Intune and Entra with PowerShell \ After the recent Crowdstrike Incident I've been thinking a lot about how to quickly perform LAPS and BitLocker actions against remote devices, and report on their use primarily via Microsoft Graph and Intune. I work and talk with a lot of folks in highly distributed environments (thinking of you, all of my EDU friends!).
  • Track File Activities in SharePoint Online Using PowerShell \ Users are given access to files in the organization for various purposes, such as project collaboration, documents sharing, and accessing necessary resources for their roles. Based on the permissions granted, users can perform actions on files and folders such as deletion, download, modifying, and more.
  • Find Your Most Frequently Used Terminal Commands \ Determine the most used commands in the terminal using Bash, Fish, PowerShell and Zsh with these simple one line commands.
  • OneDrive Pastejacking \ Phishing campaign exploits Microsoft OneDrive users with sophisticated social engineering, manipulating them into executing a malicious PowerShell script.

Books, Media, and Learning Resources

  • TEC 2024 PowerShell & Conditional Access Workshops \ Don't miss your chance to meet and learn from your favorite Practical 365 Authors at TEC 2024. As a proud sponsor of TEC, we are offering BOGO discounts on exclusive pre-con workshops with authors Michel De Rooij, Jaap Wesselius, and more!

Community

  • Unveiling the Power of Generative AI with Chrissy LeMaireq \ In this episode, Chrissy LeMaire discusses AI, her experience at PSConfEU, and her return to in-person speaking after a 5-year break. She provides an update on her book, "Generative AI for the IT Professional," and shares insights into leveraging AI beyond just conversing with ChatGPT. Chrissy also showcases a couple of interesting use cases involving AI.
  • Inside IT Automation l E06 l Bruno Buyck talks about PowerShell, PSConfEU and more \ In this "Inside IT Automation" episode Heiko has a conversation with Bruno Buyck at the PSConfEU in Antwerp. They talk about the PowerShell Conference, Bruno's PowerShell journey, PowerShell trainings, the Belgium PowerShell User Group and more.

Fun

Events

  • PowerShell Saturday NC \ Join us for PowerShell Saturday NC 2024, proudly brought to you by the Research Triangle PowerShell User Group! Mark your calendars for October 5th for this year’s gathering in Raleigh, NC.

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for July 26, 2024

Announcements!

Blogs, Articles, and Posts

  • Extract LAPS Passwords and BitLocker Keys from Active Directory \ The below PowerShell can be used to extract LAPS Passwords and BitLocker Keys from Active Directory. This was written on Friday, July 19, 2024, due to the CrowdStrike Outage. If you choose to test this PowerShell, ensure that you update the argument for the SearchBase parameter to reflect your Active Directory domain.
  • The Maddening Side of the Microsoft Graph PowerShell SDK \ All software has unique quirks, and the foibles of the Microsoft Graph PowerShell SDK are well known. But it’s much harder when the underlying foundation contributes to the craziness as described in this article. Graph pagination works in a specific way and Microsoft tunes the Graph to deliver great performance by reducing the set of properties returned for objects. Both can cause concern for developers.
  • Find orphaned GPOs via PowerShell before migrating to Intune \ Many companies have already fully transitioned to Endpoint Management Intune and no longer need GPOs (Group Policy Objects). Others are in the preparatory stages. Therefore, I would like to provide some assistance for identifying orphaned Group Policy Objects. These can be relatively easily found and, if necessary, removed using PowerShell.
  • Convert RSA XML Private Key to PEM Format with PowerShell \ Recently I was working with a particular application that used certificates to secure communication. I wanted to put the certificates into Azure KeyVault. Azure KeyVault naturally allows you to store certificates. However, it only lets you upload certificates that are in PFX (PKCS#12) or CER (DER or BASE64 encoded).… keep reading
  • PowerShell script for automated remediation for CrowdStrike issue \ I have created a Powershell script for the Crowdstrike issue for some automation purposes. you can create a WinPE ISO File to boot into and remediate the crowdstrike issue. 3. Reboot: The system should boot normally. The script: This script is designed for use in an on-premises VMware environment.

Projects, Scripts, and Modules

  • pwshBedrock v 0.9.1 \ pwshBedrock enables interfacing with Amazon Bedrock foundational models, supporting direct on-demand model calls via InvokeModel and the Converse API for supported models. It allows sending messages, retrieving responses, managing message context, displaying model information, and estimating token counts and costs. Use PowerShell to integrate generative AI applications with Amazon Bedrock.
  • ChocoLogParse v 1.0.0 \ Parses Chocolatey logs into easy to use objects.

Books, Media, and Learning Resources

  • Diagnose Network Latency with PowerShell and SQLite [OC] \ In this video you’ll see how you can use PowerShell to check for network latency between multiple endpoints. You’ll learn how to record those results into a SQLite database with a just few commands, and no need to create any underlying infrastructure. Finally, you’ll see how you can view the data in PowerShell to help identify where and when you are experiencing network latency issues.

Community

  • Interactive Shell Sessions and Language Models: Steven Bucher on Project Mercury \ In the latest episode of the PowerShell Podcast, we sit down with Microsoft PM Steven Bucher to dive into Project Mercury, a cutting-edge CLI tool designed to provide an interactive shell session for chatting with language models. Steven walks us through the functionalities of Project Mercury and how users can leverage this innovative tool. He also shares his approach to product management, reflecting on his growth in the role over the past couple of years. We explore the importance of empowering others and how it serves as a pivotal goal in Steven’s professional journey. Join us for an enlightening conversation that blends technical knowledge with leadership wisdom.
  • PowerShell Community Call - July 18th, 2024 \ The record of the July 18, 2024 PowerShell Community Call

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for July 19, 2024

Blogs, Articles, and Posts

  • Upgrading the Teams and Groups Activity Report to 6.0 \ The Teams and Groups activity report is a popular script that helps administrators identify inactive teams and groups within a Microsoft 365 tenant. The script code has been developed over the years. The last version converted to Graph API requests to improve performance. This time, the upgrade is to use the Microsoft Graph PowerShell SDK to make the code easier to maintain.
  • Getting Started with PowerShell and the ServiceNow API \ Unlock the power of ServiceNow's API! Learn how to set up your developer account, create an OAuth app, and make your first API call using PowerShell.
  • Install AWS CloudShell in a VPC \ Recently, AWS announced the general availability of CloudShell VPC support. This feature enables the creation of a CloudShell environment within a dedicated VPC, establishing secure connections to other resources in the same subnet. The CloudShell inherits the VPC network configuration without any additional modification. In this article, I will introduce CloudShell, explain the new VPC support, and outline how to install AWS CloudShell in a VPC.
  • Restoring the NVIDIA Control Panel and Tools after the Appx Package Change \ With the move from the Standard driver model to the DCH (Declarative Componentized Hardware) driver model implemented from GRID 15.0 (Windows driver version 527.41) and above, the NVIDIA Control Panel app is now distributed through the Microsoft Store as an Appx Package.
  • PowerShell PSDrive \ This is sometimes forgotten, the easy way of accessing or checking network drives, certificates, registry, variables, etc. In this blog post, I will show you what a PSDrive does and some examples of its use.
  • Practical Graph: Using GitHub Copilot for Microsoft 365 PowerShell Development \ GitHub Copilot costs $10/month. At that price level, anyone working with PowerShell should try out the AI assistance to see if it helps. But will GitHub Copilot work well with Microsoft 365 PowerShell modules like Exchange Online and the Microsoft Graph PowerShell SDK. That's what we tested and report on here.

Projects, Scripts, and Modules

  • UniGetUI (formerly WingetUI): GUI for winget, Chocolatey, and PowerShell Gallery \ UniGetUI, previously known as WingetUI, is a free GUI tool that lets you easily install and update software packages from various sources, such as Winget, Chocolatey, and PowerShell Gallery. Let me show you UniGetUI's features and how it can help you quickly set up a new computer with all the essential software.
  • A PowerShell Form Generator \ This article is an evolution of the previous, it regards not only the implementation of the package, but in particular a new paradigm with which the form objects are specified; the article is not intended to be an exhaustive explanation of the product, for this please refer to the attached documentation.

Books, Media, and Learning Resources

  • PowerShell 101 \ Reluctant to learn PowerShell? This condensed version book targets the specific topics you need to know to be successful in a real-world production environment.
  • PSDates with Matthew Dowst \ Matthew Dowst talks about PSDates, a great module for working with [DateTime] in PowerShell

Community

  • Emrys MacInally Explores PowerShell Error Handling and Module Versioning Strategies \ In this episode, we welcome back Emrys MacInally, following another successful year speaking at PSConf.EU. Emrys shares his experiences and highlights from the conference, shedding light on key discussions and takeaways. We dive deep into the importance of mental health within the PowerShell community, exploring how the community can support each other. Emrys provides insights into best practices for versioning PowerShell modules and delves into the nuances of error handling, explaining why developers should avoid using the 'throw' statement in scripts. Additionally, Emrys introduces his ErrorRecord module, which simplifies the process of creating error records, offering a practical solution for more efficient error management. Tune in for an enlightening conversation packed with valuable tips and expert advice for PowerShell enthusiasts.
  • Navigating Corporate Giants - Jeffrey Snover and the Making of PowerShell \ What if you had to fight against your company's culture to bring a revolutionary tool to life? Meet Jeffrey Snover, the Microsoft architect behind PowerShell, a command tool that transformed Windows system administration. Initially met with skepticism, Snover's idea faced resistance from a company that favored graphical interfaces. Snover's journey began with a simple mission: to make Windows as command-line

Events

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0

PowerShell Weekly for July 12, 2024

Announcements!

  • The Right Way to Replace the Remove-SPOExternalUser Cmdlet \ Microsoft says they will remove the Remove-SPOExternalUser cmdlet starting July 29. They recommend using Remove-AzureADUser as a replacement. It's a bad call because that cmdlet is part of a now-retired and soon to be deprecated module. Overall, recommendations like this make you think that Microsoft doesn’t know what’s happening across the whole of Microsoft 365. And you might be right.
  • PowerShell Elevation of Privilege Vulnerability \ This one affects all Windows versions all the way back to Windows Server 2012, so be sure to get the cumulative updates installed. CVE-2024-38047 and CVE-2024-38043 are also PowerShell Elevation of Privilege Vulnerabilities included in the cumulative patches this month.

Blogs, Articles, and Posts

  • Audit Group Policy changes in the event log using XML queries and PowerShell \ Custom views in the Event Viewer allow you to filter the metadata of log entries based on various criteria. However, these filters do not assess the content of the log entry messages. To evaluate the log messages, you can extend filters using an XPath query. The examples below demonstrate how to audit Group Policy changes with XML queries, which you can further process with PowerShell.
  • Search and delete Copilot data in Microsoft 365 \ Managing and deleting unnecessary Copilot data from Microsoft 365 is essential for reducing security risks and ensuring compliance with data protection laws like GDPR and HIPAA. This blog post will guide you through the steps to search for and delete Copilot data using eDiscovery, Graph Explorer, and PowerShell. Following these steps can enhance data hygiene and safeguard your organization against potential data breaches and legal issues.
  • PowerShell: Measure Objects (Count, Average, Sum …) \ The Measure-Object cmdlet counts objects. But it can do even more. We can calculate the sum, the average and much more. In this blog post I show a few examples with Measure-Object.
  • Office Connectors Retirement for Teams \ In June, Microsoft retired Office Connectors for SharePoint Online and Microsoft 365 Groups. Starting on August 15, they're retiring connectors for Teams. The problem is finding out which teams and channels have configured connectors. That's when PowerShell comes in handy, as we prove with a script to report which teams have connectors.
  • Using Pop-Location and Push-Location in PowerShell \ At PSConfEU, somebody asked me if I used Pop-Location and Push-Location. Well, I know it's there, but no. :) In this blog post, I will show you how to use it and that it might come in handy!
  • ViperSoftX malware covertly runs PowerShell using AutoIT scripting \ The latest variants of the ViperSoftX info-stealing malware use the common language runtime (CLR) to load and execute PowerShell commands within AutoIt scripts to evade detection. [...]
  • Low Space on EFI (System) Partition – Clean up \ Hey folks, this seems like a topic that keeps coming up, despite the fact I had assumed everyone was creating large EFI volumes (984MB) by now, but I keep finding folks who have 100MB and run into issues.
  • Practical PowerShell: Error Handling \ Writing PowerShell scripts can be a fulfilling task. After all, you write something to assist with a task or procedure so you can focus on the result, not the task itself. But what if your script tries to run an action and is unsuccessful, for example, when a user the script attempts to manipulate is invalid or the signed in account has insufficient permissions to run a cmdlet? And do not forget the peculiarities of the online world, such as a network connection dropping or an authentication token expiring.
  • Mediator Pattern using PowerShell \ The Mediator Design Pattern centralizes communication, reducing dependencies & improving maintainability. Instead of direct interactions, objects use a mediator.

Continued in the comments due to post character limits

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

1

PowerShell Weekly for June 28, 2024

Announcements!

Blogs, Articles, and Posts

  • Adding Details of Authentication Methods to the Tenant Passwords and MFA Report \ V1.2 of the User Passwords and MFA report includes the names of authentication methods registered for user accounts. V1.3 expands the amount of detail reported for each method, such as the phone number used for SMS challenges, or the email address used for SSPR. It’s a small but important detail that’s useful to administrators. However, it also comes with a potential privacy issue, so the script must handle that too.
  • Leveraging OpenAI to Enhance Pull Request Management in Azure DevOps \ Our goal is to create an automation that significantly enhances the efficiency of our development process. A service hook is triggered when a new Pull Request is created in Azure DevOps, sending a webhook to an Azure Function. This function analyzes the request body, gets all commits in the Pull Request, and sends it to Open AI’s API, which generates a Pull Request message detailing all of the proposed changes from the commits and writes it back to the Azure DevOps Pull Request.
  • Create, configure, and delete system restore points with PowerShell, vssadmin.exe, and System Properties \ System restore points allow users to roll back Windows to an earlier state if problems arise. These points capture important system files, the registry, and drivers. In addition to using the System Properties applet, you can manage system restore points with PowerShell and vssadmin.exe.
  • How to Identify MFA Deployment Source in Microsoft 365 Using PowerShell \ Have you ever felt like managing multi-factor authentication (MFA) is more of a hurdle than a security measure? Constant MFA issues can be frustrating! Here are some common MFA issues; as you read, consider how you might address these challenges.
  • Connect to the Microsoft Entra PowerShell Module \ We all know that Microsoft deprecated the Azure AD PowerShell and MSOnline PowerShell modules. So, they advise us to migrate all the scripts to the MS Graph PowerShell. But finding the equivalent cmdlets and updating the scripts can be tough. Don’t worry! Microsoft heard our struggle!
  • Using Debug and Verbose parameters in PowerShell \ It's one of those things you forget, and you can get a lot more output when running scripts that will help you find out why things are not working as you expected. This small blog post will show you how to get more verbose and debug information.
  • PowerShell: Beyond the Prompt! \ Powershell often gets overshadowed by its scripting cousin, Bash, but just like Ruby, Powershell offers a depth that goes beyond the initial impression.

Projects, Scripts, and Modules

  • PSLinux v 1.0.6 \ The RedHatSatelliteSearch PowerShell module provides functions to retrieve and manage data from a RedHat Satellite server. This module allows users to specify search filters to query and fetch information about hosts and other resources managed by the Satellite server.

Books, Media, and Learning Resources

  • Counting Files with a Specific Extension Using PowerShell \ In this tutorial, we will guide you through the process of using PowerShell to count the total number of files with a specific extension within a directory and its subdirectories. This method is highly useful for system administrators and IT professionals who need to manage and analyze large volumes of files efficiently.

Community

  • From NoWayShell to PowerShell: A Coding Transformation \ In this episode, host Andrew Pla converses with coding enthusiast Josh Hendricks (@joshooaj) about his transformative PowerShell journey - a pathway that led him from avoidance to adoration. The discussion delves into the intricacies of Joshua's PSPushover and MilestonePSTools projects, developing an understanding of their creation process. Additionally, Josh recounts his captivating experience of giving a talk on "Docs" at the prestigious PowerShell Summit. This riveting dialogue remarkably encapsulates a personal journey blending skepticism, discovery, and innovation at the heart of coding.

Fun

  • TEC 2024 PowerShell Script-Off \ TEC 2024 in Dallas (October 1-2) will once again feature the TEC PowerShell Script-Off where coders attempt to come up with the best solutions for challenges set by the judges. The challenges are all Microsoft 365 scenarios (Exchange Online, Entra ID, Teams, and SharePoint Online), so there's nothing unknown about what we'll ask people to code. Come along to TEC 2024 and compete to be the best coder in town!

Check out psweekly.dowst.dev for all past editions as well as a searchable archive.

0
Looking for feedback on my script
  • Just looking at it from the point of view of making the script more portable and easier for someone else to run, there are a few things I would address.

    The first is the Write-Host commands all over the script. I would recommend converting those to Write-Verbose. Here is a great explanation when to use Write-Host vs other outputs.

    There are also numerous Write-Output commands in the script. Anything sent to the Write-Output will be returned to the calling console. If you need to take additional actions based on the results of this script, this could cause issues. You can run into problems with the New-Item commands in there too, as they will produce output. You might consider saving them to a variable or piping to Out-Null.

    Also, there is no need to call exit and set an exit code in the way you are. If you want to write and error but have the script continue you can use, Write-Error. If you want the processing to terminate then use throw. Doing it this way will allow PowerShell’s built-in error handling to take care of the exit codes. It will also give you greater flexibility with using Error Action Preferences and using try/catch statements.

    Finally, you have a path hardcoded for the workingDir. I would suggest making this a parameter or using an environment variable as this will make it more portable. Also, when creating the log variable, you will want to use the Join-Path cmdlet instead of just joining strings.

  • PowerShell Weekly for August 23, 2024
  • Community

    • Kubernetes is Easy with Anthony Nocentino
      In this episode of the PowerShell Podcast, we sit down with Anthony Nocentino, a Senior Principal Field Solution Architect at Pure Storage, to dive deep into the world of Kubernetes. Anthony breaks down what Kubernetes is and how it fits into the modern IT landscape. We explore his fascinating career journey, from consulting and SQL Server to educating the masses on Kubernetes and Linux. Anthony also shares invaluable insights on becoming a force multiplier in your career and the critical role of mentorship and offers sage advice for anyone looking to elevate their professional path.
    • PSSaturday Karlsuhe Call for Speakers
      We are excited to announce that we are looking for speakers for the upcoming PSSaturday in Germany this November! Whether you're a first-time speaker or an experienced presenter, we welcome you to share your ideas. If you have an interesting topic and are willing to speak for up to 45 minutes, we want to hear from you.
  • PowerShell Weekly for August 23, 2024
  • Projects, Scripts, and Modules

    Books, Media, and Learning Resources

    • Build a Superfast Research Assistant using PowerShell and AI
      In this episode, I’ll show you how to combine PowerShell with AI to automate tasks, chat with your data, and build intelligent agents—all within your console and scripts.
    • Interactive Data at Your Fingertips: PowerShell AI Converts Data to Interactive HTML
      Transform your data with PowerShell and AI. In this video, Doug Finke, a 15x Microsoft MVP, shows how to use the PSAI module to convert Excel and CSV files into interactive HTML pages. You'll learn how to sort and interact with your data directly in your browser using the new ConvertTo-InteractiveHTML function. Doug walks through generating HTML tables with sortable columns and customizing them using AI. Whether you're managing large datasets or need a quick way to visualize your data, this tutorial will guide you through the process. Install the PSAI module and start making your data more dynamic.
    • How To PowerShell Code in Docker Containers
      In this video, we guide you through the process of installing and running Docker using PowerShell on Windows. Whether you're a beginner or an experienced developer, this step-by-step tutorial will help you get Docker up and running quickly and efficiently.
  • PowerShell Weekly for July 12, 2024
  • Projects, Scripts, and Modules

    • 365AutomatedLab and new companion module coming soon
      365AutomatedLab and new companion module coming soon I promise I haven’t forgotten about 365AutomatedLab, but I’ll be honest after Microsoft made the announcement of no more new Dev tenants it hurt a bit as I know how useful they are on learning and testing features and PowerShell without hurting your production environment.
    • How to Create SharePoint List & Add Columns Using PnP PowerShell?
      Recently, I developed one Power Apps application that needed a SharePoint list data source. Before running the application, the client must create the specific SharePoint list on their site. So, I wrote a Power Shell script to create the SharePoint list along columns to avoid mistakes when creating it manually.
    • PowerShell-Yayaml v0.5.0
      What's changed…
    • PSDates v1.0.4
      Tons of new stuff added including calculating sunrise and sunset time.

    Books, Media, and Learning Resources

    Community

    • Behind the Scenes at PSConf.EU: Harm Veenstra’s Experience and Insights
      In this episode of the PowerShell Podcast, we sit down with Microsoft MVP Harm Veenstra to discuss his exciting experiences at PSConf.EU, where he attended for the first time and embarked on a new journey into public speaking. Harm shares his thoughts on receiving the prestigious Microsoft MVP award and delves into his recent projects, including creating a TCP/UDP listener for testing firewall ports and using a Pi-hole to block ads on his home network. We also explore his perspectives on automation in the MSP world, the power of Microsoft Graph, and why he hasn’t yet adopted AI tools. Tune in for an engaging conversation filled with insights, tips, and highlights from PSConf.EU!
    • Write Code, Write Blogs: Lessons with Brock Bingham
      In our latest Powershell Podcast episode, we chat with Brock Bingham. We explore his transition from sysadmin to writer and his viewpoint of coding as creative problem-solving. Brock also shares insightful blogging tips and advises against the pitfalls of comparison. A must-listen for aspiring PowerShellers. (plz create a blog and share your learnings for future you)
  • PSConfEU
  • Just got a photo from one of them - what the heck are all these people doing on 5.1?...

  • PSConfEU
  • Hi @[email protected]

    I'm not going myself but sending 2 employees down there. Been attending in the early years myself, when it first was Don Jones and then Tobias Weltner running it.

    Content of the conference is very technical and can highly recommend it. Enjoy!

  • PowerShell Weekly for June 14, 2024
  • Community

    • PipeScript, Formatting, and Docker: An In-Depth Conversation with James Brundage
      In this episode of the PowerShell Podcast, we are joined by Microsoft MVP, former PowerShell team member, and module maker extraordinaire James Brundage. We hear about his experience at Microsoft Build, learn all docker and kubernetes while discussing his Rocker module, UserGroup updates, implicit interpretation in Pipescript, formatting and types, and so much more. Strap in because we go deep in this one.
    • Breaking Down ModuleFast and More with Justin Grote
      In this episode of the PowerShell Podcast, host Andrew Pla interviews Microsoft MVP and PowerShell aficionado Justin Grote. They delve into an issue in the Az.Accounts 3.0.0 module, with Justin offering insights and a workaround (use an earlier version of the module). Justin also discusses his innovative ModuleFast project, explaining its architecture and his approach to writing PowerShell scripts and modules. The conversation highlights Justin's passion for APIs and celebrates his contributions as an official PowerShell project contributor. Listeners get a glimpse into Justin's workflow working at a Managed Service Provider (MSP) and how he writes to much PowerShell. He offers valuable advice for those early in their careers. Additionally, Justin shares updates on his PowerHTML (1.2m downloads) project, which originated from a GitHub pull request, showcasing his continuous contributions to the PowerShell community.
    • PowerShell Community Call - May 16th, 2024
      Last month's community call with the PowerShell team.
  • PowerShell Weekly for June 14, 2024
  • Books, Media, and Learning Resources

  • PowerShell Weekly for June 14, 2024
  • Projects, Scripts, and Modules

    • passwordstate-management v 4.4.49
      Powershell Module for managing Password State
    • PowerQualys v 0.3.0
      Helper module for Qualys
    • WinTuner v 0.8.9
      Package and publish any apps from WinGet to Intune.
    • Interpreting Audit Records for Teams Meeting Recordings (Again)
      Three years ago, I wrote a script to analyze the audit records generated for Teams meeting recordings. Then things changed in terms of how the audit records were generated and how the Search-UnifiedAuditLog cmdlet returns audit search results. All of which meant that considerable work was needed to revamp (rewrite) the script. Maybe you need to check any script that uses the Search-UnifiedAuditLog cmdlet too?
    • tiPS v 1.3.10
      PowerShell tips delivered straight to your terminal.
  • Renaming multiple files based on a list of names
  • So it sort of worked in that it outputed a bunch of files with the names but with blank icons and not the Adobe icons. Powershell also had an error for each list item that looked like the following:

    Rename-Item : Cannot bind argument to parameter 'NewName' because it is an empty string.
    At line:1 char:86
    + ... ads\individuals.txt"; $i=0; dir | % { ren $_ "$($names[$i])"; $i++ }
    +                                                   ~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Rename-Item], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Rena
       meItemCommand
    

    Maybe the command needs '.pdf' somewhere?

  • Renaming multiple files based on a list of names
  • There's no point in having a CSV for just a single column, just make it a simple text file and it'll simplify the code a bit. So assuming you have a file called names.txt, here's a one-liner that can do the trick:

    $names = cat "\path\to\names.txt"; $i=0; dir | % { ren $_ "$($names[$i])"; $i++ }
    

    As long as the order in your text file matches the order shown by dir, you shouldn't have any issues. Maybe do a dry run with a -WhatIf to the ren first to see how the files are being renamed, before you do the actual rename. :)

  • Renaming multiple files based on a list of names
  • If the CSV file contains both the current names and the new names, this should work if you use the first line for column labels (I'm using OldName and NewName in this example):

    Import-CSV $pathToCSV | ForEach-Object { Rename-Item $_.OldName $_.NewName }

    If you just have a list of new names as a text file where the first line of the file is the new name for the first file (by name, sorted alphabetically), this should work:

    $files = Get-ChildItem -File *.pdf | Sort-Object -Property Name #I think the output of Get-ChildItem is already sorted by name, but I'm not sure
    $newNames = Get-Content $pathToTXT
    if ($files.Count -ne $newNames.Count) {
        Write-Error "The number of PDF files to be renamed does not match the number of new names"
        exit
    }
    0..($files.Count - 1) | ForEach-Object { Rename-Item $files[$_] $newNames[$_] }
    
    
  • PowerShell Weekly for Nov 17, 2023
  • Here are some possibly related communities in the instance:

    Feel free to crosspost into them or post future content on this topic there if they are relevant.
    I am a bot and this was performed automatically 🤖 For any issues contact Ategon.

  • In honor of sysadmin day, what are some of your favorite sysadmin related scripts or modules?
  • Probably this script:

    #!/bin/bash
    
    if [ -z "$1" ]
    then
            echo "Please provide git repository url as an argument for this script."
            exit 1
    fi
    regex='(https?|ftp|file)://[-[:alnum:]\+&amp;@#/%?=~_|!:,.;]*[-[:alnum:]\+&amp;@#/%=~_|]'
    if [[ $1 =~ $regex ]]
    then
    basename=$(basename $1)
    reponame=${basename%.*}
    curl -X 'POST' 'https://localgitea.com/api/v1/repos/migrate?access_token={Access Token Here}' \
      --insecure \
      -H "accept: application/json" \
      -H "Content-Type: application/json" \
      -d '{  "clone_addr": "'"$1"'",  "issues": false,  "labels": false,  "lfs": false,  "mirror": true,  "mirror_interval": "96h0m0s",  "private": false, "repo_name": "'"$reponame"'", "pull_requests": true,  "releases": true, "repo_owner": "githubpublic",  "service": "git",  "wiki": true}'
    else
            echo "Invalid URL"
            exit 1
    fi
    

    You can adjust it as needed and as for why I have --insecure flag, I have a direct network cable between my PC to the server, so encryption or HTTPS is not needed here. This is probably my favorite command, because I would write above as .sra.sh in home directory and then alias the .bashrc to make a sra command by adding alias sra=/home/{your user account}/.sra.sh in .bashrc and from there, anytime I have an interesting repository that I want to archive, I simply run sra {git url} and that's it. It also specify the mirror interval manually for 4 days interval rather than every 8 hours that would've needlessly spam the git server.

    This is something I rely on everyday both as developer and system admin, I would maintain a different supply chain and prevent a supply chain attacks by generating my own package feeds/registry automatically from Gitea/Forgejo.

    Edited to Add: I noticed this community is Powershell, here the powershell version of above:

    param (
        [Parameter(Mandatory=$true)]
        [string]$gitRepoUrl
    )
    
    function Test-Url($url) {
        $regex = "(https?|ftp|file)://[-[:alnum:]\+&amp;@#/%?=~_|!:,.;]*[-[:alnum:]\+&amp;@#/%=~_|]"
        return $url -match $regex
    }
    
    
    $basename = Split-Path $gitRepoUrl -Leaf
    $reponame = [System.IO.Path]::GetFileNameWithoutExtension($basename)
    
    $headers = @{
        'accept' = 'application/json'
        'Content-Type' = 'application/json'
    }
    
    $body = @{
        'clone_addr' = $gitRepoUrl
        'issues' = $false
        'labels' = $false
        'lfs' = $false
        'mirror' = $true
        'mirror_interval' = '96h0m0s'
        'private' = $false
        'repo_name' = $reponame
        'pull_requests' = $true
        'releases' = $true
        'repo_owner' = 'githubpublic'
        'service' = 'git'
        'wiki' = $true
    } | ConvertTo-Json
    
    Invoke-RestMethod -Uri 'https://localgitea.com/api/v1/repos/migrate?access_token={Access Token Here}' -Method POST -Headers $headers -Body $body -SkipCertificateCheck
    
    
  • Display Any Tree with PowerShell
  • Ahhhh my first Fediverse whoops! Posted with the wrong lemmy.world account I had originally used before finding programming.dev. Disregard my deleted one... let's try again 😅

    I love terminal utilis like this, but I am a huge sucker for eye candy like icons (obviously with a supported font). It would be neat if there was a param to support icons so it looks something like the output from exa, example below:

  • Display Any Tree with PowerShell
  • I am a sucker for being able to visualize a tree in the terminal but these days if I am doing that I also like when it shows icons (with a supported font). Would be a cool param to add to give that option! Something like what exa can do, example below: