Compare commits

..

26 Commits

Author SHA1 Message Date
07bf2c14ce Removed Continue in loop 2025-01-03 14:58:24 +01:00
f308f5e804 Prompt modification for when a user already exists. 2025-01-03 14:51:17 +01:00
826c49d164 Error handling and check if user exists 2025-01-03 14:26:45 +01:00
7df974133a Remove potential escape char from charset 2025-01-03 14:10:03 +01:00
e7d688f972 Change group assignment 2025-01-03 12:50:02 +01:00
842a474a80 Commit & Push test 2025-01-03 12:25:12 +01:00
7285578906 Added new permissions and groups SIDs 2025-01-03 10:32:26 +01:00
67f3e3a4fa Added comments 2025-01-02 17:37:42 +01:00
5de0e4613d Misc text added 2025-01-02 17:20:30 +01:00
1ea4f9e09c Now exports users to a csv file 2025-01-02 17:18:15 +01:00
74d891415f Renaming to match what the script does 2025-01-02 16:58:43 +01:00
15a7637596 Almost completely done 2025-01-02 16:56:26 +01:00
ec5cb7dc4a Typo fix 2024-12-31 16:53:02 +01:00
9409e59f57 Add basic user add / group add mechanisms 2024-12-31 16:52:09 +01:00
Kawawete
8ee990cca2 Add functions 2024-11-27 17:59:24 +01:00
Kawawete
d6982c4927 Command output now goes into variable $RdString 2024-11-27 17:49:06 +01:00
Kawawete
bc97219e5e Add script that generates random strings, useful for passwords 2024-11-27 17:44:55 +01:00
Kawawete
eadda6107c Mod 2024-10-17 11:02:49 +02:00
Kawawete
2dd5bd9217 Start of the Multi-Thread template project 2024-10-17 09:36:15 +02:00
Kawawete
09d5e0f281 Merge branch 'main' of https://git.azuze.fr/kawa/ps-scripts 2024-10-17 09:33:53 +02:00
Kawawete
9c7533edb0 Update 2024-10-17 09:32:16 +02:00
66bd96e180 Stuff 2024-03-13 23:24:47 +01:00
5614dcb11c Chqnged threading stuff, back to jobs 2024-03-13 23:11:49 +01:00
Kawawete
7824d55859 Undo Test 2024-03-13 17:47:01 +01:00
Kawawete
5f11213de5 Test 2024-03-13 17:46:32 +01:00
Kawawete
a42c3bf5ef Tried to integrate Threading, as by default, a lot of functionnality will hang the GUI 2024-03-13 17:41:33 +01:00
5 changed files with 279 additions and 65 deletions

View File

@@ -0,0 +1,115 @@
#On vérifie que les modules soient bien installés
if (Get-Module -ListAvailable -Name PSWriteColor) {
$modExiste = $true
}
else {
$modExiste = $false
}
#Cette étape permet de désactiver les messages de confirmation d'install
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
switch ($modExiste) {
$true{Import-Module ActiveDirectory;Import-Module PSWriteColor}
$false{Install-Module PSWriteColor -Confirm:$False;Import-Module ActiveDirectory;Import-Module PSWriteColor}
Default {Import-Module ActiveDirectory;Import-Module PSWriteColor}
}
#On crée le CSV pour y stocker les ID
$pcName = (Get-ComputerInfo).CSName
Set-Content "C:\techLogins-$pcName.csv" -Value "Username,Password"
########### Fonctions ###########
function GenPass { #Genere un mdp aléatoire selon les parametres indiqués
$TokenSet = @{
U = [Char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
L = [Char[]]'abcdefghijklmnopqrstuvwxyz'
N = [Char[]]'0123456789'
S = [Char[]]'!"#$%&()*+,-.:;<=>?@[]^_`{}~'
}
$Upper = Get-Random -Count 5 -InputObject $TokenSet.U
$Lower = Get-Random -Count 5 -InputObject $TokenSet.L
$Number = Get-Random -Count 5 -InputObject $TokenSet.N
$Special = Get-Random -Count 5 -InputObject $TokenSet.S
$StringSet = $Upper + $Lower + $Number + $Special
$RdString = (Get-Random -Count 15 -InputObject $StringSet) -join ''
return $RdString
}
function GetADSID { #On récupere le SID de l'AD pour pouvoir l'intégrer aux groupes qui en ont besoin
$fullSID = (Get-ADDomain).DomainSID.Value
$domaineSID = $fullSID.split("-",5)[-1]
return $domaineSID
}
########### Variables ###########
$userList = "Tech-N1","Tech-N2","Tech-N3"
# On récupère le SID du serveur car certains SID de groupes en ont besoin
$domaineSID = (GetADSID)
# On utilise le SID des groupes au lieu de leur noms familliers car Microsoft les traduit dans la langue cible du serveur
$grpAccountOp = "S-1-5-32-548"
$grpDomainAdm = "S-1-5-21-$domaineSID-512"
$grpPrintOp = "S-1-5-32-550"
#$grpServerOp = "S-1-5-32-549" Pas utilisé
#$grpPowerUsers = "S-1-5-32-547" Déprécié
$grpDHCPadm = "S-1-5-21-$domaineSID-1111"
$grpDHCPuser = "S-1-5-21-$domaineSID-1110"
$grpGPOadmin = "S-1-5-21-$domaineSID-520"
$grpNetAdmin = "S-1-5-32-556"
#################################
########### Script ############
#Pour chaque user, on le crée + ajoute aux bons groupes
ForEach($user in $userList){
try{
# On vérifie si l'utilisateur existe déjà, passe au suivant si oui
$existingUser = Get-ADUser -Filter { Name -eq $user } -ErrorAction SilentlyContinue
if ($existingUser) {
Write-Color -Text "L'utilisateur ", $user, " existe déjà. Application des permissions." -Color White, Yellow
}
$userPass = (GenPass)
$userEncPass = ConvertTo-SecureString -String $userPass -AsPlainText -Force
$detailsUser = @{
Name = $user
AccountPassword = $userEncPass
Enabled = $true
ChangePasswordAtLogon = $false
PasswordNeverExpires = $true #On fait en sorte qu'il n'expire pas
}
New-ADUser @detailsUser #On cree l'user...
#...puis on l'ajoute aux bons groupes
switch ($user) {
"Tech-N1"{$Groups = @($grpAccountOp,$grpPrintOp,$grpDHCPuser)}
"Tech-N2"{$Groups = @($grpAccountOp,$grpPrintOp,$grpDHCPadm,$grpGPOadmin,$grpNetAdmin)}
"Tech-N3"{$Groups = @($grpDomainAdm)}
Default {}
}
$newCsvLine = @([PSCustomObject]@{Username = $user; Password = $userPass})
$newCsvLine | Export-CSV "C:\techLogins-$pcName.csv" -Append -NoTypeInformation -Encoding UTF8
ForEach ($Group in $Groups) {
Add-ADPrincipalGroupMembership $User -MemberOf $Group
}
Write-Color -Text "L'utilisateur ",$User," a bien été crée. Son mot de passe est ",$userPass -Color White,Green,White,Cyan
}
catch {
Write-Error "Erreur pour l'utilisateur $user : $_"
}
}
Write-Color -Text "Les utilisateurs ainsi que leur mots de passes ont été exportés ici : ","C:\techLogins-$pcName.csv" -Color White,Green

17
Intune/Random-PWGen.ps1 Normal file
View File

@@ -0,0 +1,17 @@
$TokenSet = @{
U = [Char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
L = [Char[]]'abcdefghijklmnopqrstuvwxyz'
N = [Char[]]'0123456789'
S = [Char[]]'!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~'
}
$Upper = Get-Random -Count 5 -InputObject $TokenSet.U
$Lower = Get-Random -Count 5 -InputObject $TokenSet.L
$Number = Get-Random -Count 5 -InputObject $TokenSet.N
$Special = Get-Random -Count 5 -InputObject $TokenSet.S
$StringSet = $Upper + $Lower + $Number + $Special
$RdString = (Get-Random -Count 15 -InputObject $StringSet) -join ''
#You can use now $RdString in your script to make a random password to an AD user or other stuff...

View File

@@ -0,0 +1,7 @@
# This is a template for multi-threaded stuff, or at least it should be...
# We start a new job and store it in a variable to be able to display said job later by invoking the variable in the Receive-Job cmdlet.
$Job = Start-Job -ScriptBlock {Write-Output 'Hello World'}
Receive-Job $Job # Will display Hello World in the cmd

View File

@@ -0,0 +1,11 @@
{
"configurations": [
{
"name": "PowerShell: Launch Script",
"type": "PowerShell",
"request": "launch",
"script": "${workspaceFolder}\\sputils.ps1",
"args": []
}
]
}

View File

@@ -12,13 +12,25 @@
# Source : C:\Users\SebastienQUEROL\source\repos\sharepointmover-gui\Form1.Designer.cs # Source : C:\Users\SebastienQUEROL\source\repos\sharepointmover-gui\Form1.Designer.cs
################################################################################ ################################################################################
function Get-ScriptDirectory ###############Thread Setup
{ #Return the directory name of this script
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$ScriptPath = Get-ScriptDirectory $Global:syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState ="STA"
$newRunspace.ThreadOptions ="ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
###########################
##Aucune foutre idée de ce qu'est cense faire ce morceau de code, ca a été généré par le createur de forms
# function Get-ScriptDirectory
# { #Return the directory name of this script
# $Invocation = (Get-Variable MyInvocation -Scope 1).Value
# Split-Path $Invocation.MyCommand.Path
# }
# $ScriptPath = Get-ScriptDirectory
###
# Chargement des assemblies externes # Chargement des assemblies externes
Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Windows.Forms
@@ -209,7 +221,7 @@ $BconnectSP.UseVisualStyleBackColor = $true
# #
$URLTenant.Location = New-Object System.Drawing.Point(22, 55) $URLTenant.Location = New-Object System.Drawing.Point(22, 55)
$URLTenant.Name = "URLTenant" $URLTenant.Name = "URLTenant"
$URLTenant.Text = "https://perlinpimpim-admin.sharepoint.com" $URLTenant.Text = "https://guycarlier.sharepoint.com"
$URLTenant.Size = New-Object System.Drawing.Size(325, 20) $URLTenant.Size = New-Object System.Drawing.Size(325, 20)
$URLTenant.TabIndex = 1 $URLTenant.TabIndex = 1
# #
@@ -364,7 +376,7 @@ $tabPage5.UseVisualStyleBackColor = $true
$LresultsMove.HideSelection = $false $LresultsMove.HideSelection = $false
$LresultsMove.Location = New-Object System.Drawing.Point(8, 173) $LresultsMove.Location = New-Object System.Drawing.Point(8, 173)
$LresultsMove.Name = "LresultsMove" $LresultsMove.Name = "LresultsMove"
$LresultsMove.FullRowSelect = true #$LresultsMove.FullRowSelect = true
$LresultsMove.Size = New-Object System.Drawing.Size(776, 190) $LresultsMove.Size = New-Object System.Drawing.Size(776, 190)
$LresultsMove.TabIndex = 7 $LresultsMove.TabIndex = 7
$LresultsMove.AutoSize = $true $LresultsMove.AutoSize = $true
@@ -384,77 +396,126 @@ $FMain.Text = "SharePoint Utils GUI"
#Onglet Move #Onglet Move
##Lister les sites dans les comboBoxes ##Lister les sites dans les comboBoxes
#### On lance le ScriptBlock dans un runspace au clic du bouton BlistSites
$BlistSites.Add_Click({ $BlistSites.Add_Click({
#On vide la variable pnpConnection pour ne pas avoir de faux positifs $newRunspace =[runspacefactory]::CreateRunspace()
$pnpConnection=$Null $newRunspace.ApartmentState ="STA"
#On stocke la derniere connection PnP $newRunspace.ThreadOptions ="ReuseThread"
$pnpConnection = Get-PnPConnection | Out-string $newRunspace.Open()
#A ameliorer, mais pour l'instant, ca devrait passer $newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
if(-not ([string]::IsNullOrEmpty($pnpConnection))){
$CBdestSite.Items.Clear() $BlistSitesRunSpace = [PowerShell]::Create().AddScript({
$CBsourceSite.Items.Clear()
$sitesList = $null #On vide la variable pnpConnection pour ne pas avoir de faux positifs
$sitesList = Get-PnPTenantSite | Where -Property Template -NotIn ("SRCHCEN#0", "REDIRECTSITE#0", "SPSMSITEHOST#0", "APPCATALOG#0", "POINTPUBLISHINGHUB#0", "EDISC#0", "STS#-1", 'EHS#1','POINTPUBLISHINGTOPIC#0') | Select url $pnpConnection=$Null
$LresultsMove.Items.Clear() #On stocke la derniere connection PnP
foreach($siteUrl in $sitesList){ $pnpConnection = Get-PnPConnection | Out-string
$siteUrl -match "@{Url=(?<content>.*)}" #A ameliorer, mais pour l'instant, ca devrait passer
$siteUrlClean = $matches["content"] if(-not ([string]::IsNullOrEmpty($pnpConnection))){
$CBsourceSite.Items.Add([string]$siteUrlClean) $CBdestSite.Items.Clear()
$CBdestSite.Items.Add([string]$siteUrlClean) $CBsourceSite.Items.Clear()
} $sitesList = $null
} $sitesList = Get-PnPTenantSite | Where-Object -Property Template -NotIn ("SRCHCEN#0", "REDIRECTSITE#0", "SPSMSITEHOST#0", "APPCATALOG#0", "POINTPUBLISHINGHUB#0", "EDISC#0", "STS#-1", 'EHS#1','POINTPUBLISHINGTOPIC#0') | Select-Object url
elseif(([string]::IsNullOrEmpty($pnpConnection))){ $LresultsMove.Items.Clear()
$LresultsMove.Items.Clear() foreach($siteUrl in $sitesList){
$LresultsMove.Items.Add("Connectez-vous au tenant d'abord") $siteUrl -match "@{Url=(?<content>.*)}"
$siteUrlClean = $matches["content"]
$CBsourceSite.Items.Add([string]$siteUrlClean)
$CBdestSite.Items.Add([string]$siteUrlClean)
}
} }
else{ elseif(([string]::IsNullOrEmpty($pnpConnection))){
$LresultsMove.Items.Clear() $LresultsMove.Items.Clear()
$LresultsMove.Items.Add("Connectez-vous au tenant d'abord") $LresultsMove.Items.Add("Connectez-vous au tenant d'abord")
} }
else{
$LresultsMove.Items.Clear()
$LresultsMove.Items.Add("Connectez-vous au tenant d'abord")
}
})
$BlistSitesRunSpace.PowerShell.Runspace = $newRunspace
$BlistSitesRunSpace.Thread = $BlistSitesRunSpace.PowerShell.BeginInvoke()
}) })
##Bouger les dossiers ##Bouger les dossiers
# $copyIt = {
# param ($sourceSite,$destSite)
# $sourceSite = $sourceSite -Replace '[A-Za-z]+://([A-Za-z]+(\.[A-Za-z]+)+)',''
# $destSite = $destSite -Replace '[A-Za-z]+://([A-Za-z]+(\.[A-Za-z]+)+)',''
# $jobCopyPending = Copy-PnPFile -SourceUrl "$sourceSite" -TargetUrl "$destSite" -Force -OverwriteIfAlreadyExists
# $jobStatus = Receive-PnPCopyMoveJobStatus -Job $jobCopyPending -Wait
# Write-Output $jobStatus
# }
$Bgo.Add_Click({ $Bgo.Add_Click({
$sourceSite = $CBsourceSite.Text
$destSite = $CBdestSite.Text
$jobMovePending = Copy-PnPFile -SourceUrl $sourceSite -TargetUrl $destSite -Force -OverwriteIfAlreadyExists $newRunspace =[runspacefactory]::CreateRunspace()
$jobStatus = Receive-PnPCopyMoveJobStatus -Job $jobMovePending $newRunspace.ApartmentState ="STA"
Write-Host $jobStatus $newRunspace.ThreadOptions ="ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
$copySPRunspace.PowerShell = [PowerShell]::Create().AddScript({
$destSite = $CBdestSite.Text
$sourceSite = $CBsourceSite.Text
$sourceSite = $sourceSite -Replace '[A-Za-z]+://([A-Za-z]+(\.[A-Za-z]+)+)',''
$destSite = $destSite -Replace '[A-Za-z]+://([A-Za-z]+(\.[A-Za-z]+)+)',''
$jobCopyPending = Copy-PnPFile -SourceUrl "$sourceSite" -TargetUrl "$destSite" -Force -OverwriteIfAlreadyExists
$jobStatus = Receive-PnPCopyMoveJobStatus -Job $jobCopyPending -Wait
Write-Output $jobStatus
})
$copySPRunspace.PowerShell.Runspace = $newRunspace
$copySPRunspace.Thread = $copySPRunspace.PowerShell.BeginInvoke()
}) })
#Onglet Parametres #Onglet Parametres
##Connexion Sharepoint ##Connexion Sharepoint
$pnpConnection=$null
$pnpConnection = Get-PnPConnection | Out-string
$tenantURL = $URLTenant.Text
$BconnectSP.Add_Click({ $BconnectSP.Add_Click({
$pnpConnection=$null Disconnect-PnPOnline
$pnpConnection = Get-PnPConnection | Out-string $newRunspace =[runspacefactory]::CreateRunspace()
$tenantURL = $URLTenant.Text $newRunspace.ApartmentState ="STA"
$connResults = Connect-PnPOnline -Url $tenantURL -Interactive 2>&1 | Out-String $newRunspace.ThreadOptions ="ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
Switch ($ERROR) $connectToSPRunspace.PowerShell = [PowerShell]::Create().AddScript({
{ Connect-PnPOnline -Url $tenantURL -Interactive | Out-String
{$ERROR[0] -match "Host not reachable" }{
$label4.Text = "Injoignable"
$label4.ForeColor = [System.Drawing.Color]::MediumVioletRed
Break}
{$ERROR[0] -match "User canceled authentication."}{
$label4.Text = "Annulé"
$label4.ForeColor = [System.Drawing.Color]::MediumVioletRed
Break}
{-not ([string]::IsNullOrEmpty($pnpConnection))}{
$label4.Text = "Connecté"
$label4.ForeColor = [System.Drawing.Color]::Green
}
Default {
$label4.Text = "Connecté"
$label4.ForeColor = [System.Drawing.Color]::Green
}
}
}) Switch ($ERROR)
{
{$ERROR[0] -match "Host not reachable" }{
$label4.Text = "Injoignable"
$label4.ForeColor = [System.Drawing.Color]::MediumVioletRed
Break}
{$ERROR[0] -match "User canceled authentication."}{
$label4.Text = "Annulé"
$label4.ForeColor = [System.Drawing.Color]::MediumVioletRed
Break}
{-not ([string]::IsNullOrEmpty($pnpConnection))}{
$label4.Text = "Connecté"
$label4.ForeColor = [System.Drawing.Color]::Green
}
Default {
$label4.Text = "Connecté"
$label4.ForeColor = [System.Drawing.Color]::Green
}
}
})
$connectToSPRunspace.PowerShell.Runspace = $newRunspace
$connectToSPRunspace.Thread = $connectToSPRunspace.PowerShell.BeginInvoke()
})
function OnFormClosing_FMain{ function OnFormClosing_FMain{
@@ -471,6 +532,9 @@ function OnFormClosing_FMain{
$FMain.Add_FormClosing({ $FMain.Add_FormClosing({
#Disconnect-PnPOnline #Disconnect-PnPOnline
Write-Host "Goodbye, come again soon :*" Write-Host "Goodbye, come again soon :*"
$RunspacePool.Close()
$RunspacePool.Dispose()
[gc]::Collect()
OnFormClosing_FMain OnFormClosing_FMain
}) })