r/PowerShell • u/DerBootsMann • Jul 28 '19
Script Sharing PowerShell Tutorial Mini-Course (Free)
r/PowerShell • u/DerBootsMann • Jul 28 '19
r/PowerShell • u/Astrochotic • Apr 18 '23
# Please Run CreateNewBorn.ps1 as Administrator
$Parents = @(Get-Parent | Where-Object {$_.Name -eq "Austin, Eliz"})
# Initialize Baby
$Baby = New-Person -TypeName Boy -Source $Parents.DNA
$Baby | Add-Attribute -Name "Cuteness" -Value "MAX"
$Baby.Love = "Full"
# Start Life
Start-Process -FilePath "Life.exe" -LoadUserProfile $Baby
Write-Output "Congratulations!"r/PowerShell • u/compwiz32 • Dec 23 '20
Hello PowerShell peeps!
I write an article showing how to use the SecretsManagament module from Micosoft.
Learn how to manage your passwords and secrets from your PowerShell cmd prompt. I'll show you how to install, config and use the Microsoft SecretsManagement module in your daily workflow.
Feedback is always welcome. Happy holidays!
https://4sysops.com/archives/secretsmanagement-module-for-powershell-save-passwords-in-powershell/
r/PowerShell • u/ryan-jan • Jun 09 '21
Hi all,
I recently posted an in-depth overview of the many uses of PowerShell splatting. Hopefully there is something useful in it for everyone. So, check it out at the link below and let me know what you think in the comments!
https://ryanjan.uk/powershell-splatting/
Cheers!
r/PowerShell • u/Skunklabz • Aug 05 '20
r/PowerShell • u/ktzouv • Jun 12 '20
r/PowerShell • u/PsCustomObject • Nov 23 '19
desert zealous homeless butter elderly connect voiceless compare touch sand
This post was mass deleted and anonymized with Redact
r/PowerShell • u/ricardovaras_99 • Apr 08 '24
I’m getting into the shell and language. People in this sub helped me get finally committed to learning the language (here) and now I want to ask you what was your learning process, what resources did you used, and why you started with PS.
r/PowerShell • u/Mental_Patient_1862 • Jan 15 '21
Posted this in a reply to a separate thread but posting here to maybe get more folks onboard.
I truly wish folks would stop using aliases when helping people with code. Many (most?) of the questions here (and other forums) are from posters that are new to Powershell. Aliases just add another layer of confusion. As for me, I don't use them because 99% of what I do with PoSh is with scripts and using aliases in scripts makes them much harder to read. So yeah, I have to look them up too.
It's awesome that more experienced coders are willing to share their skill, it just seems to me it'd be awesomer if they would go that tiny extra mile to write out ForEach-Object instead of %, or Where-Object instead of ?, etc.
</whinge>
r/PowerShell • u/dus0922 • Oct 06 '19
I love powershell. At my primary job, I use it daily to save me and my team time. However, I also do alot of side jobs for a little hometown PC repair shop.
I took on a project hourly, so I knew what I was getting into. This job was mainly installing an AV Server, removing stand-alone AV from workstations, and then installing the agent from the new server. Easy-peasy... had I done it manually, each station 1 at a time, it probably would have taken few hours at least. But I scripted almost the whole thing, without realizing that I was screwing myself out of those extra hours.
TL;DR. Took on a job hourly. Used powershell to do it quickly and efficiently, Cost myself several hours pay.
r/PowerShell • u/[deleted] • May 07 '18
r/PowerShell • u/[deleted] • Jan 05 '17
r/PowerShell • u/sup3rmark • Mar 15 '16
function Get-AsciiShrug {
$OutputEncoding = [System.Text.Encoding]::unicode
write-output "¯_($(0x30C4|%{[char]$_}))_/¯" | clip
}r/PowerShell • u/Possible-Bowler-2352 • Jan 03 '22
Happy new year fellow redditors.
A new year means new surprises from your favorite software editor, Microsoft, right ?
If any of you are running on premise exchange mail system, you may encounter some issues within your emails, starting on the 1st.
Seeing every mail marked as DEFERRED when coming from a well deserved 2 days break where you cannot even rest a bit due to the festivities arround ?
That's how I like my first monday of the year, no coffee time this morning and already a queue full of critical level tickets.
Anyway, a patch script has been shared in order to correct this issue and get everything running on.
https://aka.ms/ResetScanEngineVersion or Link to the post.
Don't forget to set your execution policy to remotely signed before running the script or you'll run into some trouble:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Edit : If you want to keep track of the mails being delivered once you run the script, you can look at your message queue.
1..10 | % { get-queue | where identity -like "*submission*"; sleep -Seconds 5}
Best of luck y'all and I wish you the best for 2022
r/PowerShell • u/johnhammond010 • Dec 06 '19
r/PowerShell • u/thebeersgoodnbelgium • Jul 08 '19
My previous post got a lot of traction so I turned the script into a module. kbupdate is now available in the PowerShell Gallery and on GitHub. It's code-signed, xplat and now uses -UseBasicParsing (thanks /u/jantari!) It also has a new command Get-KbUpdate


Enjoy! Please file any issues or PRs here: https://github.com/potatoqualitee/kbupdate
If anyone has regex skills, that'd be welcomed. Otherwise, the module does use some old school split parsing. It'd be nice if Microsoft just fixed their RSS feed though.
r/PowerShell • u/mikefrobbins • Oct 03 '18
r/PowerShell • u/[deleted] • Nov 28 '21
r/PowerShell • u/ZebulaJams • Apr 28 '21
Maybe I'm doing this to inflate my ego, but oh well.
EDIT 1: Here is the github link that some of you requested. I'm new to GitHub so if something is wrong, let me know and I will change it! :)
TL;DR - I wrote a script for our HR department so my group didn't have to do their portion of their job. However our system is picky with passwords so I ended up not using it. But it was fun.
I'm 4 months new to my current company as a SysAdmin and recently there was a discussion that HR doesn't have the proper permissions to add new employee information into our system (which I thought was somewhat strange, but oh well). They usually pop and email over to me and my two coworkers to add the employee into our system. I had some extra time so I thought, "I'm going to see if I can script this".
Basically the script populates a form that asks for the employee ID, first name, last name, labor class, time type and shop. After that is all entered, it populates a separate form where the HR user can add the necessary roles for the new employee (timecard, employee type, etc.)
All the data gets added to our SQL database which houses all of the employee information as well as some other things. Once that has been added, if the user were to look in the actual system for the employee they would see all of their information properly set up. Was pretty slick, I thought.
Here is the code:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
## BUILDING THE FORM
##############################################################################################################################
## Position Variables
$okXPosition = 110
$okYPosition = 780
#
$cancelXPosition = 260
$cancelYPosition = 780
#
$formWidth = 500
$formHeight = 900
#
$loginLabelXPosition = 47
$loginLabelYPosition = 20
$loginFieldXPosition = 50
$loginFieldYPosition = 55
#
$empFirstLabelXPosition = 47
$empFirstLabelYPosition = 95
$empFirstXPosition = 50
$empFirstYPosition = 130
#
$empLastLabelXPosition = 47
$empLastLabelYPosition = 170
$empLastXPosition = 50
$empLastYPosition = 210
#
$laborClassLabelXPosition = 47
$laborClassLabelYPosition = 250
$laborClassFieldXPosition = 50
$laborClassFieldYPosition = 290
#
$empTypeLabelXPosition = 47
$empTypeLabelYPosition = 330
$empTypeMenuXPosition = 50
$empTypeMenuYPosition = 370
#
$roleLabelXPosition = 47
$roleLabelYPosition = 510
$roleMenuXPosition = 50
$roleMenuYPosition = 600
#
$timeTypeLabelXPosition = 47
$timeTypeLabelYPosition = 330
$timeTypeMenuXPosition = 50
$timeTypeMenuYPosition = 370
#
$shopLabelXPosition = 47
$shopLabelYPosition = 460
$shopMenuXPosition = 50
$shopMenuYPosition = 500
## Form itself
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "AiM Employee Form"
$objForm.Size = New-Object System.Drawing.Size($formWidth,$formHeight)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({
if ($_.KeyCode -eq "Enter" -or $_.KeyCode -eq "Escape"){
$objForm.Close()
}
})
<#
## OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(110,550)
$OKButton.Size = New-Object System.Drawing.Size(110,60)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
#$OKButton.Add_Click({$objForm.Close()})
$objForm.AcceptButton = $OKButton
$objForm.Controls.Add($OKButton)
#>
## OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point($okXPosition,$okYPosition)
$OKButton.Size = New-Object System.Drawing.Size(110,60)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$objForm.AcceptButton = $OKButton
$objForm.Controls.Add($OKButton)
###
## Cancel Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point($cancelXPosition,$cancelYPosition)
$CancelButton.Size = New-Object System.Drawing.Size(110,60)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
#$CancelButton.Add_Click({$objForm.Close()})
$objForm.CancelButton = $CancelButton
$objForm.Controls.Add($CancelButton)
###
## Employee ID/Login label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($loginLabelXPosition,$loginLabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,30)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Employee ID"
$objForm.Controls.Add($objLabel)
## Login field
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size($loginFieldXPosition,$loginFieldYPosition)
$objTextBox.Size = New-Object System.Drawing.Size(400,20)
#$objTextBox.Multiline = $true
$objTextBox.Font = New-Object System.Drawing.Font("Lucinda",16,[System.Drawing.FontStyle]::Regular)
#$objTextBox.Text = "(Employee ID)"
$objForm.Controls.Add($objTextBox)
###
## Employee first name label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($empFirstLabelXPosition,$empFirstLabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,30)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Employee First Name"
$objForm.Controls.Add($objLabel)
## Employee first Name field
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Size($empFirstXPosition,$empFirstYPosition)
$objTextBox2.Size = New-Object System.Drawing.Size(400,20)
$objTextBox2.Font = New-Object System.Drawing.Font("Lucinda",16,[System.Drawing.FontStyle]::Regular)
#$objTextBox2.Text = "(Employee Name)"
$objForm.Controls.Add($objTextBox2)
###
## Employee last name label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($empLastLabelXPosition,$empLastLabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,30)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Employee Last Name"
$objForm.Controls.Add($objLabel)
## Employee last Name field
$objTextBox3 = New-Object System.Windows.Forms.TextBox
$objTextBox3.Location = New-Object System.Drawing.Size($empLastXPosition,$empLastYPosition)
$objTextBox3.Size = New-Object System.Drawing.Size(400,20)
$objTextBox3.Font = New-Object System.Drawing.Font("Lucinda",16,[System.Drawing.FontStyle]::Regular)
#$objTextBox2.Text = "(Employee Name)"
$objForm.Controls.Add($objTextBox3)
###
## Labor Class Label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($laborClassLabelXPosition,$laborClassLabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,30)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Labor Class"
$objForm.Controls.Add($objLabel)
## Labor Class Field
$objTextBox4 = New-Object System.Windows.Forms.TextBox
$objTextBox4.Location = New-Object System.Drawing.Size($laborClassFieldXPosition,$laborClassFieldYPosition)
$objTextBox4.Size = New-Object System.Drawing.Size(400,20)
$objTextBox4.Font = New-Object System.Drawing.Font("Lucinda",16,[System.Drawing.FontStyle]::Regular)
#$objTextBox2.Text = "(Employee Name)"
$objForm.Controls.Add($objTextBox4)
###
## Time type label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($timeTypeLabelXPosition,$timeTypeLabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,30)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Select Time Type"
$objForm.Controls.Add($objLabel)
## Time type menu
$listbox2 = New-Object System.Windows.Forms.ListBox
$listbox2.Location = New-Object System.Drawing.Point($timeTypeMenuXPosition,$timeTypeMenuYPosition)
$listbox2.Size = New-Object System.Drawing.Size(400,20)
$listbox2.Font = New-Object System.Drawing.Font("Lucinda",12,[System.Drawing.FontStyle]::Regular)
$listbox2.Height = 90
[void] $listBox2.Items.Add('REGULAR')
[void] $listBox2.Items.Add('OVERTIME')
[void] $listBox2.Items.Add('COMP EARNED')
[void] $listBox2.Items.Add('OVERDBL')
[void] $listBox2.Items.Add('SAFETY OVT')
[void] $listBox2.Items.Add('SAFETY COMP')
[void] $listBox2.Items.Add('COMPDBL')
$objForm.Controls.Add($listBox2)
## Help/label prompt for SHOP
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($shopLabelXPosition,$shopLabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,40)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Select Shop"
$objForm.Controls.Add($objLabel)
## Drop down menu for SHOP
$listBox1 = New-Object System.Windows.Forms.ListBox
$listBox1.Location = New-Object System.Drawing.Point($shopMenuXPosition,$shopMenuYPosition)
$listBox1.Size = New-Object System.Drawing.Size(400,20)
$listBox1.Font = New-Object System.Drawing.Font("Lucinda",12,[System.Drawing.FontStyle]::Regular)
$listBox1.Height = 270
#$listBox.SelectionMode = 'MultiExtended'
[void] $listBox1.Items.Add('ADMIN')
[void] $listBox1.Items.Add('BUSSERV')
[void] $listBox1.Items.Add('CARPENTERS')
[void] $listBox1.Items.Add('CEP')
[void] $listBox1.Items.Add('COMMISSION')
[void] $listBox1.Items.Add('CUSTSERV')
[void] $listBox1.Items.Add('D&C')
[void] $listBox1.Items.Add('DIRECTOR')
[void] $listBox1.Items.Add('DISTRIBUTE')
[void] $listBox1.Items.Add('ELECTRICAL')
[void] $listBox1.Items.Add('ENERGYMGMT')
[void] $listBox1.Items.Add('EQUIPOPER')
[void] $listBox1.Items.Add('EVENTUTILS')
[void] $listBox1.Items.Add('FINISHES')
[void] $listBox1.Items.Add('FM')
[void] $listBox1.Items.Add('HIGHVOLT')
[void] $listBox1.Items.Add('HVAC')
[void] $listBox1.Items.Add('LABGAS')
[void] $listBox1.Items.Add('LIFTMAINT')
[void] $listBox1.Items.Add('LOAM')
[void] $listBox1.Items.Add('LOCKSMITH')
[void] $listBox1.Items.Add('MAINTADMIN')
[void] $listBox1.Items.Add('MIS')
[void] $listBox1.Items.Add('MOVING')
[void] $listBox1.Items.Add('PARTEAM')
[void] $listBox1.Items.Add('PLANNING')
[void] $listBox1.Items.Add('PLUMBERS')
[void] $listBox1.Items.Add('PROJ&ENGR')
[void] $listBox1.Items.Add('PROJECTS')
[void] $listBox1.Items.Add('PURCHASING')
[void] $listBox1.Items.Add('RCDEMGR')
[void] $listBox1.Items.Add('RECEIVING')
[void] $listBox1.Items.Add('RECPOSTAGE')
[void] $listBox1.Items.Add('RECYCLING')
[void] $listBox1.Items.Add('SAFETY')
[void] $listBox1.Items.Add('SECURITY')
[void] $listBox1.Items.Add('SNOW REMOVAL')
[void] $listBox1.Items.Add('STORAGE')
[void] $listBox1.Items.Add('SUPPTADMIN')
[void] $listBox1.Items.Add('SURPLUS')
[void] $listBox1.Items.Add('UTILADMIN')
[void] $listBox1.Items.Add('UTILITIES')
[void] $listBox1.Items.Add('WAREHOUSE')
[void] $listBox1.Items.Add('WASTEMGMT')
[void] $listBox1.Items.Add('WATERQLTY')
$objForm.Controls.Add($listBox1)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
#[void]$objForm.ShowDialog()
$result = $objForm.ShowDialog()
## Add results to variables and display data ONLY if 'OK' is pressed
##############################################################################################################################
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$Login = $objTextBox.Text ## Employee ID
$FirstName = $objTextBox2.Text ## First Name
$LastName = $objTextBox3.Text ## Last Name
$LaborClass = $objTextBox4.Text ## Labor Class
$Description = $objTextBox2.Text + " " + $objTextBox3.Text ## Description = first name and last name
$EmployeeID = $objTextBox.Text ## Employee ID
$Password = "P@$$w0rd" ## Password
$EmployeeType = "S"
$TimeType = $listbox2.SelectedItem
$Shop = $listBox1.SelectedItem ## Employee Shop
#$Shop = $objTextBox4.Text
#$Role = @($listBox.SelectedItems)
## Confirm variables. Used for testing
<#
$Login
$FirstName
$LastName
$Description
$Password
$LaborClass
$EmployeeID
$EmployeeType
$TimeType
$Shop
#$Shop
#$Role
#$Role.GetType()#>
## Sql Statement to insert employee information
$EmployeeInfo = "INSERT INTO table1 (login, description, password, employee_id, shop, default_org, active)
VALUES ('$Login', '$Description', '$Password', '$EmployeeID', '$Shop', 'N', 'Y')
"
## Pass query to SQL Server & return results
$Pass = Invoke-Sqlcmd -Query $EmployeeInfo -ServerInstance "SERVER IP" -Username "USERNAME" -Password "PASSWORD"
#$Pass
## Sql statement to insert values into HR table
$HRTable = "INSERT INTO table2 (shop_person, fname, lname, time_type, labor_class, active, emp_type)
VALUES ('$Login', '$FirstName', '$LastName', '$TimeType', '$LaborClass', 'Y', '$EmployeeType')
"
## Pass query to SQL
$EmployeeProfileUpdate = Invoke-Sqlcmd -Query $HRTable -ServerInstance "SERVER IP" -Username "USERNAME" -Password "PASSWORD"
} ## End 'IF' Statement
## ROLES Prompt now that the user has been added
##############################################################################################################################
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
## Perform this task until the "finish" button is pressed
do
{
## Position Variables
$doneXPosition = 360
$doneYPosition = 400
$cancelXPosition = 360
$cancelYPosition = 400
$addXPosition = 50
$addYPosition = 400
$formWidth = 500
$formHeight = 530
$LabelXPosition = 100
$LabelYPosition = 20
$roleMenuXPosition = 50
$roleMenuYPosition = 120
## Form itself
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "AiM Employee Roles"
$objForm.Size = New-Object System.Drawing.Size($formWidth,$formHeight)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({
if ($_.KeyCode -eq "Enter" -or $_.KeyCode -eq "Escape"){
$objForm.Close()
}
})
## Done Button
$DoneButton = New-Object System.Windows.Forms.Button
$DoneButton.Location = New-Object System.Drawing.Point($doneXPosition,$doneYPosition)
$DoneButton.Size = New-Object System.Drawing.Size(90,35)
$DoneButton.Text = 'Finish'
$DoneButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$objForm.AcceptButton = $DoneButton
$objForm.Controls.Add($DoneButton)
<#
## Cancel Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size($cancelXPosition,$cancelYPosition)
$CancelButton.Size = New-Object System.Drawing.Size(90,35)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
###>
## Add Button
$AddButton = New-Object System.Windows.Forms.Button
$AddButton.Location = New-Object System.Drawing.Point($addXPosition,$addYPosition)
$AddButton.Size = New-Object System.Drawing.Size(90,35)
$AddButton.Text = 'Add'
$AddButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$objForm.AcceptButton = $AddButton
$objForm.Controls.Add($AddButton)
## Label/help
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size($LabelXPosition,$LabelYPosition)
$objLabel.Size = New-Object System.Drawing.Size(325,80)
$objLabel.Font = New-Object System.Drawing.Font("Lucinda",14,[System.Drawing.FontStyle]::Regular)
$objLabel.Text = "Select one Role at a time then press 'Add'. Press 'Finish' when done."
$objForm.Controls.Add($objLabel)
## Drop down menu for ROLES
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point($roleMenuXPosition,$roleMenuYPosition)
$listBox.Size = New-Object System.Drawing.Size(400,20)
$listBox.Font = New-Object System.Drawing.Font("Lucinda",12,[System.Drawing.FontStyle]::Regular)
$listBox.Height = 260
#$listBox.SelectionMode = 'MultiExtended'
[void] $listBox.Items.Add('SHOP_FOREMAN')
[void] $listBox.Items.Add('SHOP_PERSON')
[void] $listBox.Items.Add('TIME_CARD')
[void] $listBox.Items.Add('EXEMPT')
[void] $listBox.Items.Add('HOURLY')
[void] $listBox.Items.Add('NON-EXEMPT')
$objForm.Controls.Add($listBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
#[void]$objForm.ShowDialog()
$result2 = $objForm.ShowDialog()
## If the user presses "add", add roles to specified user
if ($result2 -eq [System.Windows.Forms.DialogResult]::OK)
{
$Role = @($listBox.SelectedItems)
#$Role
## Sql Statement to add Roles to specified user
$EmployeeRoles = "INSERT INTO table3 (role_id, login)
VALUES ('$Role', '$Login')
SELECT t3.role_id, t3.login
FROM
table3 t3
INNER JOIN
table1 t1 ON (t3.login = t1.login)
WHERE
t1.login = '$Login'
"
$ExecuteRoleQuery = Invoke-Sqlcmd -Query $EmployeeRoles -ServerInstance "SERVER IP" -Username "USERNAME" -Password "PASSWORD"
}
} while ($result2 -ne [System.Windows.Forms.DialogResult]::Cancel)
}
#>I started using PS2EXE to create this into an executable as well as an 'installation script' for the HR department (this script obviously requires SqlServer Module and some other things) and was feeling pretty good. Alas, the password portion of the script was a bust. I found out that our system only stores passwords into the database that were set WITHIN the system itself, not by updating the database on the backend. Everything else still works, however this would mean that my group would still have to log in and change the password, defeating the purpose of the script.
Oh well though. It was a fun project and I get to keep it for reference for a possible future project and who knows what else.
r/PowerShell • u/smarthomepursuits • Feb 24 '21
r/PowerShell • u/patdaddy007 • Feb 04 '21
function Pure-Evil{
DO {
IF ((Get-clipboard) -gt $null){Set-Clipboard $null}
} while ($True)
}Bonus points if used during a remote support session w/ a vendor
r/PowerShell • u/pcgeek86 • Oct 06 '20
r/PowerShell • u/TheFutureIsAwesome21 • Apr 09 '18
r/PowerShell • u/hamsumwich • Jun 09 '25
I had posted this earlier, but wasn't satisfied with the contents of the body. What follows is the message I should have given to clearly explain a problem I was trying to solve. What follows is my story.
I recently downloaded 100 GB of media files from my Google Drive. Since the files dated back over twenty years, I had to use their Google Takeout service. It packaged all of my files into fifty separate 2 GB zipped files. It was a pain to download all of them, and the process worsened after unzipping them.
The folder structure is the zipped folder as the root. Under that is another individual folder for Takeout. The next subfolder is Google Photos. As you enter that folder, you'll find many folders organized by year. As you enter each folder, you'll find all the media file types that you've been storing over the years. Among them are dozens of JSON files. I initiated a manual process of sorting by file type, selecting all JSON files, deleting them, and then moving all the remaining files to a single folder for media storage.
While this manual process worked, I found that as I transitioned from one set of uncompressed folders to another and moved the files out, numerous duplicate name conflicts arose. I needed to automate the renaming of each file.
I'm no expert in PowerShell, but I've come to utilize AI to help create simple scripts that automate redundant administrative tasks. The first script I received help with was to traverse all subfolders and delete all JSON files recursively. That was easy.
Next, I went about renaming files. I wanted to use the Date and Time that the file was created. However, not all of my files had that information in their metadata, as shown by the file property details. After further investigation, I discovered a third-party command-line tool called ExifTool. Once I downloaded and configured that, I found that the metadata I wanted to look for was an attribute called DateTimeOriginal. However, I also discovered that many of my older files lacked that information and were effectively blank. So, I had to come up with a way to rename them without causing conflict. I asked AI to randomly generate an eight-character name using uppercase letters and numbers 0-9. For the majority of files, I used a standard naming convention of YYYY-MM-DD_HH-MM_HX.fileType. Obviously, that was for Year, Month, Hour, Minute, and two HEX characters, which I had randomly generated. I asked AI to help me set up this script to go through a folder and rename all media files recursively. It worked great.
As I worked through more file renaming and consolidating, I realized I needed another folder to store all subfolder media files, rename them, and then move them to a final media folder. That was to avoid constantly renaming files that were already renamed. Once all media files in the temporary folder have been renamed, the script moves them to the final media storage folder.
As I developed what was initially three scripts, I reached a point where I felt confident that they were working smoothly. I then asked AI to help stitch them all together and provide a GUI for all steps, including a progress window for each one, as well as a .CSV log file to document all changes. This part became an iterative exercise, as it required addressing numerous errors and warnings. Ultimately, it all came together. After multiple tests on the downloaded Google media, it appears to be an effective script. It may not be the most elegant, but I'm happy to share it with this community. This script works with any Windows folder structure and is not limited to just Google media file exports.
That holistic media move/rename/store script follows:
EDIT: I realized after the fact that I also wanted to log file size in its proper format. So, I updated the script to capture that information for the CVS log as well. That component is in this updated script below.
EDIT 2: I've improved the PS interface, updating it with each process and data output, as well as enhancing the progress bar for each task to display (x/y).
# ============================================
# MASTER MEDIA FILE ORGANIZATION SCRIPT
# ============================================
# This script requires that ExifTool by Phil Harvey is on your computer and it's referenced in your enviornmental variables System PATH.
# You can download ExifTool at: https://exiftool.org/
# See https://exiftool.org/install.html for more installation instructions.
# Once installed, test it by running PowerShell and typing exiftool, and hit Enter. If it runs, you're golden!
Add-Type -AssemblyName System.Windows.Forms
function Show-ProgressWindow {
param (
[string]$Title,
[string]$TaskName,
[int]$Total
)
$form = New-Object System.Windows.Forms.Form
$form.Text = $Title
$form.Width = 400
$form.Height = 100
$form.StartPosition = "CenterScreen"
$label = New-Object System.Windows.Forms.Label
$label.Text = "$TaskName (0/$Total)"
$label.AutoSize = $true
$label.Top = 10
$label.Left = 10
$form.Controls.Add($label)
$progressBar = New-Object System.Windows.Forms.ProgressBar
$progressBar.Minimum = 0
$progressBar.Maximum = $Total
$progressBar.Value = 0
$progressBar.Width = 360
$progressBar.Height = 20
$progressBar.Left = 10
$progressBar.Top = 30
$form.Controls.Add($progressBar)
$form.Show()
return @{ Form = $form; ProgressBar = $progressBar; Label = $label }
}
function Write-Teal($text) {
Write-Host $text -ForegroundColor Cyan
}
function Write-Yellow($text) {
Write-Host $text -ForegroundColor Yellow
}
function Write-Green($text) {
Write-Host $text -ForegroundColor Green
}
function Write-White($text) {
Write-Host $text -ForegroundColor White
}
# Banner
Write-Green "=============================="
Write-Green "Media File Organization Script"
Write-Green "=============================="
# Folder selections
Add-Type -AssemblyName System.Windows.Forms
$folderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
$folderBrowser.Description = "Select the folder where your original media files are located"
$null = $folderBrowser.ShowDialog()
$sourcePath = $folderBrowser.SelectedPath
$folderBrowser.Description = "Select the folder to stage files for renaming"
$null = $folderBrowser.ShowDialog()
$stagingPath = $folderBrowser.SelectedPath
$folderBrowser.Description = "Select the final folder to store renamed files"
$null = $folderBrowser.ShowDialog()
$finalPath = $folderBrowser.SelectedPath
foreach ($path in @($sourcePath, $stagingPath, $finalPath)) {
if (-not (Test-Path $path)) {
New-Item -ItemType Directory -Path $path | Out-Null
}
}
# Step 1: Delete JSON Files
$jsonFiles = Get-ChildItem -Path $sourcePath -Recurse -Filter *.json
if ($jsonFiles.Count -gt 0) {
$progress = Show-ProgressWindow -Title "Deleting JSON Files" -TaskName "Processing" -Total $jsonFiles.Count
$count = 0
foreach ($file in $jsonFiles) {
Remove-Item -Path $file.FullName -Force
$count++
$progress.ProgressBar.Value = $count
$progress.Label.Text = "Processing ($count/$($jsonFiles.Count))"
[System.Windows.Forms.Application]::DoEvents()
}
Start-Sleep -Milliseconds 500
$progress.Form.Close()
}
Write-Host ""
Write-White "Processed $($jsonFiles.Count) JSON files.`n"
# Step 2: Move to Staging
Write-Yellow "Step 1: Moving files to staging folder..."
$mediaExtensions = @(
"*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.tif", "*.tiff", "*.webp",
"*.heic", "*.raw", "*.cr2", "*.nef", "*.orf", "*.arw", "*.dng", "*.rw2", "*.pef", "*.sr2",
"*.mp4", "*.mov", "*.avi", "*.mkv", "*.wmv", "*.flv", "*.3gp", "*.webm",
"*.mts", "*.m2ts", "*.ts", "*.vob", "*.mpg", "*.mpeg"
)
$filesToMove = @()
foreach ($ext in $mediaExtensions) {
$filesToMove += Get-ChildItem -Path $sourcePath -Filter $ext -Recurse
}
$progress = Show-ProgressWindow -Title "Moving Files" -TaskName "Processing" -Total $filesToMove.Count
$count = 0
foreach ($file in $filesToMove) {
Move-Item -Path $file.FullName -Destination (Join-Path $stagingPath $file.Name) -Force
$count++
$progress.ProgressBar.Value = $count
$progress.Label.Text = "Processing ($count/$($filesToMove.Count))"
[System.Windows.Forms.Application]::DoEvents()
}
Start-Sleep -Milliseconds 500
$progress.Form.Close()
Write-White "Successfully moved $count files.`n"
# Step 3: Rename Files
Write-Yellow "Step 2: Renaming files..."
function Get-RandomName {
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
-join ((1..8) | ForEach-Object { $chars[(Get-Random -Minimum 0 -Maximum $chars.Length)] })
}
function Get-ReadableFileSize($size) {
if ($size -ge 1GB) { return "{0:N2} GB" -f ($size / 1GB) }
elseif ($size -ge 1MB) { return "{0:N2} MB" -f ($size / 1MB) }
else { return "{0:N2} KB" -f ($size / 1KB) }
}
$timestampTracker = @{}
$global:LogOutput = @()
$global:logPrefix = (Get-Date -Format "yyyy-MM-dd_HH-mm")
$renameTargets = @()
foreach ($ext in $mediaExtensions) {
$renameTargets += Get-ChildItem -Path $stagingPath -Filter $ext -Recurse
}
$progress = Show-ProgressWindow -Title "Renaming Files" -TaskName "Processing" -Total $renameTargets.Count
$count = 0
$metadataCount = 0
$randomCount = 0
foreach ($file in $renameTargets) {
try {
$ext = $file.Extension.ToLower()
$dateRaw = & exiftool -q -q -DateTimeOriginal -s3 "$($file.FullName)"
$fileSizeReadable = Get-ReadableFileSize $file.Length
$newName = ""
if ($dateRaw) {
$dt = [datetime]::ParseExact($dateRaw, "yyyy:MM:dd HH:mm:ss", $null)
$timestampKey = $dt.ToString("yyyy-MM-dd_HH-mm")
$hexSuffix = "{0:X2}" -f (Get-Random -Minimum 0 -Maximum 256)
$newName = "$timestampKey" + "_$hexSuffix$ext"
$metadataCount++
} else {
$newName = "$(Get-RandomName)$ext"
$randomCount++
}
$collisionPath = Join-Path $file.DirectoryName $newName
while (Test-Path $collisionPath) {
$randomTag = Get-Random -Minimum 1000 -Maximum 9999
$newName = $newName.Replace($ext, "_$randomTag$ext")
$collisionPath = Join-Path $file.DirectoryName $newName
}
Rename-Item -Path $file.FullName -NewName $newName -ErrorAction Stop
$global:LogOutput += [PSCustomObject]@{
Timestamp = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Action = "Renamed"
OriginalName = $file.Name
NewName = $newName
OriginalFilePath = $sourcePath
FinalFilePath = $finalPath
FileSize = $fileSizeReadable
RenameType = if ($dateRaw) { "Metadata" } else { "Random" }
}
} catch {
continue
}
$count++
$progress.ProgressBar.Value = $count
$progress.Label.Text = "Processing ($count/$($renameTargets.Count))"
[System.Windows.Forms.Application]::DoEvents()
}
Start-Sleep -Milliseconds 500
$progress.Form.Close()
Write-White "Renamed $metadataCount files using metadata, $randomCount files with random names.`n"
# Step 4: Final Move
Write-Yellow "Step 3: Moving to final destination..."
$finalFiles = @()
foreach ($ext in $mediaExtensions) {
$finalFiles += Get-ChildItem -Path $stagingPath -Filter $ext -Recurse
}
$progress = Show-ProgressWindow -Title "Moving Files" -TaskName "Processing" -Total $finalFiles.Count
$count = 0
foreach ($file in $finalFiles) {
Move-Item -Path $file.FullName -Destination (Join-Path $finalPath $file.Name) -Force
$count++
$progress.ProgressBar.Value = $count
$progress.Label.Text = "Processing ($count/$($finalFiles.Count))"
[System.Windows.Forms.Application]::DoEvents()
}
Start-Sleep -Milliseconds 500
$progress.Form.Close()
Write-White "Successfully moved $count files.`n"
# Save log
$logCsvPath = Join-Path $finalPath ($global:logPrefix + "_LOG.csv")
$global:LogOutput |
Select-Object Timestamp, Action, OriginalName, NewName, OriginalFilePath, FinalFilePath, FileSize, RenameType |
Export-Csv -Path $logCsvPath -NoTypeInformation -Encoding UTF8
# Summary Output
Write-Green "======= PROCESSING SUMMARY ========"
Write-Teal "Files renamed using metadata : $metadataCount"
Write-Teal "Files renamed with random ID : $randomCount"
Write-Teal "Total files renamed : $(($metadataCount + $randomCount))"
Write-Teal "Files moved to final folder : $count"
Write-Green "==================================="
Write-Teal "`nDetailed log saved to: $logCsvPath"
Write-Green "`nProcessing completed successfully!`n"