I'm new to any sort of programming at all and I've been working on this tool, but I've finally hit a wall. I've read every article, post, and watched every video I could find but runspaces just aren't making sense to me. All I'm trying to do is get the auto search function to run on separate thread to keep the main window from locking up. I've been stuck on this for so long now that I considered ditching Powershell to start learning Python, but I'd rather understand this than quit. I think I even understand how to set the function to run on a separate runspace but the specific part that I don't understand is how to run the UI in it's own runspace and have the two communicate. I've even tried using some boilerplate with a syncHash table but I could never get it working. I'd really appreciate any help before I go insane.
All Files:
https://mega.nz/folder/251yHaBJ#bHYNYdNfAmia5mEhE5IOKQ
Powershell script in question:
#Xaml import
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$xamlFile = "MainWindow.xaml"
$inputXAML = Get-Content -Path $xamlFile -Raw
$inputXAML = $inputXAML -replace 'mc:Ignorable="d"','' -replace "x:N","N" -replace '^<Win.*','<Window'
[XML]$XAML = $inputXAML
$reader = New-Object System.Xml.XmlNodeReader $XAML
try {
$psform = [Windows.Markup.XamlReader]::Load($reader)
}
catch {
Write-Host $_.Exception
throw
}
$xaml.SelectNodes("//*[#Name]") | ForEach-Object {
try {
Set-Variable -Name "var_$($_.Name)" -Value $psform.FindName($_.Name) -ErrorAction Stop
}
catch {
throw
}
}
#Functions
function autoSearch {
$Drives = Get-PSDrive -PSProvider "FileSystem"
$a1 = foreach ($Drive in $Drives) {Get-ChildItem -Path $Drive.Root -Recurse -ErrorAction SilentlyContinue -Directory -Filter "Steam"}
$a2 = Get-ChildItem (Join-Path $a1.FullName "userdata") -ErrorAction SilentlyContinue -Directory
$a3 = Get-ChildItem (Join-Path $a2.FullName "*") -ErrorAction SilentlyContinue -Directory -Filter "1446780"
if ($a3) {
$var_saveR.Foreground = "Green"
$var_saveR.Content = "Found"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 3000
}
$timer.add_Tick({$var_saveR.Content = ""})
$var_loc1.Content = $a3
$filePath = "Config.txt"
$lineNumber = "1"
$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] = $a3.FullName + "\*"
$fileContent | Set-Content $filePath -Force
}
else {
$var_saveR.Foreground = "Red"
$var_saveR.Content = "Not Found"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 7000
}
$timer.add_Tick({$var_saveR.Content = ""})
}
}
function manualSave {
Add-Type -AssemblyName System.Windows.Forms
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$browser.ShowDialog()
$var_loc1.Content = $browser.SelectedPath
$filePath = "Config.txt"
$lineNumber = "1"
$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] = $var_loc1.Content + "\*"
$fileContent | Set-Content $filePath -Force
}
function manualBack {
Add-Type -AssemblyName System.Windows.Forms
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$browser.ShowDialog()
$var_loc2.Content = $browser.SelectedPath
$filePath = "Config.txt"
$lineNumber = "2"
$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] = $var_loc2.Content + "\*"
$fileContent | Set-Content $filePath -Force
}
function backup {
$file = "Config.txt"
$a1 = Get-Content $file
$a1[0]
$a1[1]
Copy-Item $a1[0] ($a1[1] -replace '\\\*','') -Recurse
$var_backupStatus.Foreground = "Green"
$var_backupStatus.Content = "Done"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 5000
}
$timer.add_Tick({$var_backupStatus.Content = ""})
}
function restore {
$file = "Config.txt"
$a1 = Get-Content $file
$a1[0]
$a1[1]
Copy-Item $a1[1] ($a1[0] -replace '\\\*','') -Recurse #-Confirm
$var_restoreStatus.Foreground = "Green"
$var_restoreStatus.Content = "Done"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 5000
}
$timer.add_Tick({$var_restoreStatus.Content = ""})
}
#UI
$var_aSearchButton.Add_Click({autoSearch})
$var_mSetButton1.Add_Click({manualSave})
$var_mSetButton2.Add_Click({manualBack})
$var_backupButton.Add_Click({backup})
$var_restoreButton.Add_Click({restore})
$var_loc1.Content = (Get-Content "Config.txt" -TotalCount 1) -replace '\\\*',''
$var_loc2.Content = (Get-Content "Config.txt" -TotalCount 2)[-1] -replace '\\\*',''
$psform.ShowDialog() | Out-Null
i have the following code:
cls
Get-Module -ListAvailable | Import-Module
Import-Module ActiveDirectory
$Groups = Get-ADGroup -Filter {name -like 'XYZ'} | select name -
ExpandProperty name
$i=0
$tot = $Groups.count
$Table = #()
$Record = #{
"Group Name" = ""
"Name" = ""
"username" = ""
}
Foreach ($Group in $Groups) {
#// Set up progress bar
$i++
$status = "{0:N0}" -f ($i / $tot * 100)
Write-Progress -Activity "Exporting AD Groups" -status "Processing
Group $i of $tot : $status% Completed" -PercentComplete ($i / $tot *
100)
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive |
select name, SamAccountName
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."username" = $Member.SamAccountName
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
Write-Host $Table
which works perfectly but i want to list all duplicates in the $Record."Name" = $Member.name with specific group so for example:
username=barry is duplicated in GROUP XYZ
i tried already the following:
ForEach ($Element in $Table)
{
If (($Table -match $Element).count -gt 1)
{
"Duplicates detected"
}
}
The simplest answer is to just pipe $Table to Group-Object and filter for groups with a count greater than one at the end as such:
$Table | Group 'Group Name','Name' | Where{$_.Count -gt 1}
If you are looking to do this in the middle of your loop you could do so by grouping the results of Get-ADGroupMember, but I think it'll probably be faster to do it all at the end.
You could simply keep track of the members using a hashtable:
$seen = #{};
foreach ($Member in $Arrayofmembers)
{
if($seen[$Member.Name])
{
Write-Host "$($Member.Name) is duplicated in group $Group";
}
else
{
$seen.Add($Member.Name, $true);
}
# ... rest of the loop
}
The the set of code below, everything works except 1 thing I can not figure out.
while Get-CSUserStandardsValidatedSet is processing the data, The object count array stays in tact. whether I have 1 or 100 object in the array the count is good. But when Get-CSUserStandardsValidatedSet passes the object array via return $return back to the Caller Function Invoke-MRC_CSSkypeObjects_ImportCSV. The Object count Doubles everytime.
If I pass the parameter Select -unique I actually loose records I want to process.
Any Ideas?
Function Get-CSUserStandardsValidatedSet
{
param ($users)
[array]$UserInfoArray = #()
$DNStandardGlobalCpAnswer = $null
$DNStandardGlobalCuAnswer = $null
$SIPStandardGlobalCpAnswer = $null
$UMMStandardGlobalAnswer = $null
foreach ($user in $users)
{
$PhoneNumberIsInUse = $false
$UserInfoCopy = New-UserInfo
######################################################## #Still Need to validate the correct OU Location Based on AccountTypes# ########################################################
Write-host "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
Write-Host "$($user.DisplayName) $($user.CSVtelephoneNumber) $user"
Write-host "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
#This must be populated for OU Validation, and Cu DisplayName Validation
$UserInfoCopy.AllowRecordToConinueNoErrorsFound = $true
Write-Host 'SiteCode'
$UserInfoCopy.CSVSiteCode = $user.SiteCode
Write-host "$($UserInfoCopy.CSVSiteCode)"
$UserInfoCopy.CSVPrivateSiteCode = $user.SiteCode -replace "[^0-9]" #To be removed and replaced with CSVSiteCode
Write-host "$($UserInfoCopy.CSVPrivateSiteCode)"
#if ($user.SiteCode -match "^\d+$")
# { $user.SiteCode -replace "[^0-9]"}
# else { write-host "Site Code is not numeric or does not exist: $($user.PrivateSiteCode)";end}
Write-Host 'Acct Type (U, Cu, Cp, F, H)'
$UserInfoCopy.CSVAccountTypes =
Switch ($user.AccountTypes)
{
'U' {$user.AccountTypes}
'F' {$user.AccountTypes}
'Cu' {$user.AccountTypes}
'Cp' {$user.AccountTypes}
'H' {$user.AccountTypes}
default {"Unknown Type of Skype Account to create: $($user.AccountTypes) for $($UserInfoCopy.DisplayName) ";stop}
}
Write-host "$($UserInfoCopy.CSVAccountTypes)"
Write-Host 'Private or Public'
$UserInfoCopy.CSVPhoneExtensionType_S_P = if ($user.PhoneExtensionType_S_P -eq 'S') {$true} else {$false}
Write-host "$($UserInfoCopy.CSVPhoneExtensionType_S_P)"
Write-Host 'OU'
$UserInfoCopy.CSVOU = Get-VerifyOUbyTypeForADLocation -Type $UserInfoCopy.CSVAccountTypes -SiteCode $UserInfoCopy.CSVSiteCode -OU $user.CSVOU
Write-host "$($UserInfoCopy.CSVOU)"
#region PHONE NUMBER AND POLICY OR PLAN AND POOL
Write-Host 'Telephone Number'
$UserInfoCopy.CSVtelephoneNumber =
if ((Exists-PhoneNumberisUnUsed -PhoneNumber ($user.telephoneNumber -replace "[^0-9]")))
{$user.telephoneNumber -replace "[^0-9]"}
else
{
#write-host "Telephone Number $($User.telephoneNumber) is already in use. Please remove the number from active use or change the phone number being assigned."; break
$PhoneNumberIsInUse = $True
$user.telephoneNumber -replace "[^0-9]"
}
Write-host $UserInfoCopy.CSVtelephoneNumber
Write-Host 'Ext'
$UserInfoCopy.CSVExt = $user.Ext -replace "[^0-9]"
Write-host $UserInfoCopy.CSVExt
Write-Host 'Dial Plan'
$UserInfoCopy.CSVDialPlan = if (Exists-VoiceOrDataPlanTorF -Exists_Plan $User.DialPlan -VoiceSearch $false)
{$user.DialPlan}
else {write-host "User: $($user.DisplayName) DialPlan: $($user.DialPlan) - DOES NOT EXIST";
if (($user.AccountTypes -eq 'U') -or ($user.AccountTypes -eq 'Cu') -or ($user.AccountTypes -eq 'Cp'))
{Break}
else {write-host ' Not a User/Common Area Phone Account, Allowed to Continue'} #Do not proceed if Dial Plan can not be found
}
Write-host $UserInfoCopy.CSVDialPlan
Write-Host 'Voice Policy'
$UserInfoCopy.CSVVoicePolicy = if (Exists-VoiceOrDataPlanTorF -Exists_Plan $user.VoicePolicy -VoiceSearch $true)
{$user.VoicePolicy}
else {write-host "User: $($user.DisplayName) VoicePolicy: $($user.VoicePolicy) - DOES NOT EXIST";
if (($user.AccountTypes -eq 'U') -or ($user.AccountTypes -eq 'Cu') -or ($user.AccountTypes -eq 'Cp'))
{Break}
else {write-host ' Not a User/Common Area Phone Account, Allowed to Continue'} #Do not proceed if Voice Policy can not be found
}
Write-host $UserInfoCopy.CSVVoicePolicy
Write-Host 'UM Mailbox Policy'
$UserInfoCopy.CSVUMMailboxPolicy = Get-UMMailPolicyAssigned -Type $UserInfoCopy.CSVAccountTypes -RequestUMMailboxPolicyAssign $user.UMMailboxPolicy
Write-host $UserInfoCopy.CSVUMMailboxPolicy
############################################################################################################################
#REGISTRAR POOL
Write-Host 'RegistrarPool'
$UserInfoCopy.CSVRegistrarPool = if ((Exists-MRCCSSkypeRegistrarPool -PoolCheck $user.RegistrarPool) -or ($user.AccountTypes -eq 'U'))
{$user.RegistrarPool}
else {write-host "User: $($user.DisplayName) RegistrarPool: $($user.RegistrarPool) - DOES NOT EXIST";
if (($user.AccountTypes -eq 'Cu') -or ($user.AccountTypes -eq 'Cp'))
{Break}
else {write-host 'Not a User Account, Allowed to Continue'}
}
Write-host $UserInfoCopy.CSVRegistrarPool
#PHONE NUMBER
#Private -replace "[^0-9]"
#$UserInfoCopy.PrivateExtension = $PrivSiteExtNumber + $UserInfoCopy.CSVExt
Write-Host 'Private Extension'
$UserInfoCopy.PrivateExtension = $UserInfoCopy.CSVExt -replace "[^0-9]"
Write-host $UserInfoCopy.PrivateExtension
#New Logic
#Due to the variable ways private extensions are assigned, it will be up to the user to put the correct private extension into the csv file
#Old Logic
#if (($user.SiteCode -match "^\d+$") -and ($UserInfoCopy.CSVExt -match "^\d+$")) {($user.SiteCode -replace "[^0-9]") + ($UserInfoCopy.CSVExt -replace "[^0-9]")} else {" Site Code is not a numeric number $($user.SiteCode) or Private Extension is not a numeric number $($user.CSVExt)";break}
Write-Host 'LineURI Private'
$UserInfoCopy.LineuriPrivate = [String]::Format('tel:+{0:###########};ext={1:####}',([int64]$UserInfoCopy.CSVtelephoneNumber -replace "[^0-9]"),[int64]$UserInfoCopy.PrivateExtension -replace "[^0-9]")
Write-host $UserInfoCopy.LineuriPrivate
Write-Host 'Telephone Number Private'
$UserInfoCopy.telephoneNumberPrivate_Format1 = [String]::Format('tel:{0:+#-###-###-####};ext={1:####}',[int64]$UserInfoCopy.CSVtelephoneNumber,[int64]$UserInfoCopy.PrivateExtension -replace "[^0-9]")
Write-host $UserInfoCopy.telephoneNumberPrivate_Format1
$UserInfoCopy.telephoneNumberPrivate_Format2 = [String]::Format('{0:(###) ###-####};ext={1:####}',([int64]$UserInfoCopy.CSVtelephoneNumber - 10000000000),[int64]$UserInfoCopy.PrivateExtension -replace "[^0-9]")
Write-host $UserInfoCopy.telephoneNumberPrivate_Format2
#Not Private
Write-Host 'LineURI Public'
$UserInfoCopy.Lineuri = [String]::Format('tel:+{0:###########};ext={1:####}',([int64]$UserInfoCopy.CSVtelephoneNumber),$UserInfoCopy.CSVtelephoneNumber.Substring(($UserInfoCopy.CSVtelephoneNumber.Length-4)))
Write-host $UserInfoCopy.Lineuri
Write-Host 'telephone Number Public'
$UserInfoCopy.telephoneNumber_Format1 = [String]::Format('{0:+#-###-###-####}',[int64]$UserInfoCopy.CSVtelephoneNumber)
Write-host $UserInfoCopy.telephoneNumber_Format1
$UserInfoCopy.telephoneNumber_Format2 = [String]::Format('{0:(###) ###-####}',([int64]$UserInfoCopy.CSVtelephoneNumber - 10000000000))
Write-host $UserInfoCopy.telephoneNumber_Format2
#endregion
#region NAME SECTION
#First and Last name we only care about if Cu since AD User account is being Created
#Last name must exist for Cp to generate the sip
Write-Host 'Last Name'
$UserInfoCopy.CSVLastName =
if ((($user.AccountTypes -eq 'Cu') -or ($user.AccountTypes -eq 'Cp')) -and ($user.LastName -eq ''))
{
if($CSVPhoneExtensionType_S_P)
{$UserInfoCopy.telephoneNumber_Format2}
else
{$UserInfoCopy.telephoneNumberPrivate_Format2}
#"Error no Last name for $($user.DisplayName)";stop
}
else {$user.LastName}
Write-host $UserInfoCopy.CSVLastName
Write-Host 'First Name'
$UserInfoCopy.CSVFirstName =
if (($user.AccountTypes -eq 'Cu') -or ($user.AccountTypes -eq 'Cp'))
{
if ($UserInfoCopy.CSVSiteCode -match "^\d+$")
{
$MySiteCode = $UserInfoCopy.CSVSiteCode -replace "[^0-9]"
"BR$($MySiteCode.ToString("000"))"
}
Else
{
"BR$($UserInfoCopy.CSVSiteCode)"
}
}
else {$user.FirstName}
Write-host $UserInfoCopy.CSVFirstName
Write-Host 'Display Name'
$UserInfoCopy.CSVDisplayName = Get-DisplayName -Type $UserInfoCopy.CSVAccountTypes -DisplayNameRequest $user.DisplayName `
-IsSiteNotPrivateExtension $UserInfoCopy.CSVPhoneExtensionType_S_P -Extension $UserInfoCopy.PrivateExtension `
-PublicNumber $UserInfoCopy.CSVtelephoneNumber -PrivateNumber $UserInfoCopy.CSVtelephoneNumber `
-SiteCode $UserInfoCopy.CSVSiteCode -LastName $UserInfoCopy.CSVLastName
Write-host $UserInfoCopy.CSVDisplayName
#endregion
#region SAM ACCOUNT
Write-Host 'SAM Account Name'
$MySAM = Get-UserSAMAccountName -Type $UserInfoCopy.CSVAccountTypes -SAM $User.SamAccountName -DisplayName $UserInfoCopy.CSVDisplayName -LastName $UserInfoCopy.CSVLastName -FirstName $UserInfoCopy.CSVFirstName
$UserInfoCopy.CSVSamAccountNameFound = if ($MySAM.SamAccountName.Length -ne 0) {$true} else {$false}
Write-host 'AD Account Found: ' + $UserInfoCopy.CSVSamAccountNameFound
$UserInfoCopy.CSVSamAccountName = $MySAM.SamAccountName
Write-host $UserInfoCopy.CSVSamAccountName
#Phone Number is already in use
if (($PhoneNumberIsInUse) -and ($UserInfoCopy.CSVSamAccountNameFound))
{
If
(
(
( (get-csuser $UserInfoCopy.CSVSamAccountName).lineuri -eq $UserInfoCopy.LineuriPrivate ) -and ($UserInfoCopy.CSVPhoneExtensionType_S_P -eq $False)
) `
-or
(
( (get-csuser $UserInfoCopy.CSVSamAccountName).lineuri -eq $UserInfoCopy.Lineuri ) -and ($UserInfoCopy.CSVPhoneExtensionType_S_P -eq $True)
)
)
{
#The current user is assigned the phone number and we are allowed to Proceed
#Nothing needs done to allow this
}
else
{
"Telephone Number $($User.telephoneNumber) is already in use. Please remove the number from active use or change the phone number being assigned."; "This record will not be Processed"
#Phone number is in use
#We do not want the script to stop rather ignore the user account
$UserInfoCopy.CSVSamAccountNameFound = $false #This is a partial solution as it will only stop User Account Modifications not the others
$UserInfoCopy.AllowRecordToConinueNoErrorsFound = $false #This will be a new parameter used
}
#write-host "Telephone Number $($User.telephoneNumber) is already in use. Please remove the number from active use or change the phone number being assigned."; break
}
$UserInfoCopy.telephoneNumberOriginal = $MySAM.telephoneNumberOrigional
Write-host $UserInfoCopy.telephoneNumberOriginal
$UserInfoCopy.CSVMail = $MySAM.mail
Write-host $UserInfoCopy.CSVMail
$UserInfoCopy.info = $MySAM.info
Write-host $UserInfoCopy.info
Write-Host 'SIP'
$UserInfoCopy.CSVSIP =
if ($UserInfoCopy.CSVPhoneExtensionType_S_P)
{
Get-SIPAddress -Type $UserInfoCopy.CSVAccountTypes -SAM $UserInfoCopy.CSVSamAccountName -LastName $UserInfoCopy.CSVLastName -FirstName $UserInfoCopy.CSVFirstName -SiteCode $UserInfoCopy.CSVSiteCode -LineURI $UserInfoCopy.Lineuri
}
else
{
Get-SIPAddress -Type $UserInfoCopy.CSVAccountTypes -SAM $UserInfoCopy.CSVSamAccountName -LastName $UserInfoCopy.CSVLastName -FirstName $UserInfoCopy.CSVFirstName -SiteCode $UserInfoCopy.CSVSiteCode -LineURI $UserInfoCopy.LineuriPrivate
}
Write-host $UserInfoCopy.CSVSIP
#endregion
if ($User.ExtensionAttribute7.length -ne 0)
{
$UserInfoCopy.CSVExtensionAttribute7 = [String]::Format('+{0:#-###-###-####}',([int64]($User.ExtensionAttribute7 -replace "[^0-9]")))
}
Write-host $UserInfoCopy.CSVExtensionAttribute7
$UserInfoCopy | Select-Object -Property *
Write-Host '#####################################################'
$UserInfoCopy | Select-Object -Property * | Write-Host
Write-Host '#####################################################'
Write-Host ($UserInfoCopy | Select-Object -Property *)
$UserInfoArray += $UserInfoCopy
}
$UserInfoArray | Export-CSV $LOG_csv
#$UserInfoArray | Export-CSV $LOG_csv
$return = $UserInfoArray
Return $return
}
Function Invoke-MRC_CSSkypeObjects_ImportCSV
{
param ($Import_CSVFile = $Import_CSV, [bool]$ValidateOnly = $false, $Export_ValidatedObjectCSVFile = $LOG_csv)
$FileNameTranscript = "C:\ScriptOut\Transcript-SkypeObject-CompanyPolicies-$((get-date).toString(‘yyyyMMdd-HHmmss’)).log"
Start-Transcript -Path $FileNameTranscript -Append
########################################################################################################
### IMPORT CSV AND VALIDATE INFORMATION ACCORDING TO STANDARDS ###
########################################################################################################
Write-Host '---------------------------------------------------------------------------------------------------------------------------------------------'
Write-Host ' Validating the CSV File'
Write-Host '---------------------------------------------------------------------------------------------------------------------------------------------'
$UserInfoArraySet = ''
$CSVusers=Import-Csv $Import_CSVFile
$UserInfoArraySet = (Get-CSUserStandardsValidatedSet -users $CSVusers | Select -Unique)
$UserInfoArraySet | Export-CSV $Export_ValidatedObjectCSVFile
if ($ValidateOnly -eq $false)
{
Set-MRC_SkypeWorkFlow_ProcessObjectModification -users $UserInfoArraySet
}
Else
{ #Return the Validate object Details
Return $UserInfoArraySet
}
Stop-Transcript
}
Ok so I have my first ever powershell script and it works exactly how I want it to. The output was just to a txt file and it was bland.
Totally reworked it to give all results into a single array.
mind you there maybe a better way to do this or I may have put too much code so suggestions welcomed....
my end goal is a html with just 2 rows.... Item and Result
this is ran on a machine that will get registry settings, services startup types and local acct status.
I just cant figure out how to do a table and cycle through the arrays.
thanks for your help as it is greatly apprecaited!!!!
# Static array of registry keys
$RegKeys = #("DisableNotificationCenter","AutoConfiURL","HibernateEnabled","HideSCAHealth","NoDriveTypeAutoRun","TurnOffSidebar","EnableBaloonTips","UseDomainNameDevolution","DomainNameDevolutionlevel","*.one.ads","*","SearchOrderConfig","NoAutoRebootWithLoggedOnUsers","DisabledComponents","fAllowToGetHelp","fDenyTSConnections","EnableLUA","dontdisplaylastusername")
#Static array of service names
$Services = #("LanmanServer","MPSSVC","WinDefend","WSCSVC","TRKWKS","NAPAGENT","WUAUSERV")
#Static array of users
$Users = #("Admin","Guest")
#Registry Keys
$dnc = 'HKCU:\Software\Policies\Microsoft\Windows\Explorer'
if (Test-Path $dnc) {$dnc = (Get-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer").DisableNotificationCenter}
else {$dnc = "Key not Found"}
$acu = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
if (Test-Path $acu) {$acu = (Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings").AutoConfigURL}
else {$acu = "Key not Found"}
$he = 'HKLM:\SYSTEM\CurrentControlSet\Control\Power'
if (Test-Path $he) {$he = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Power").HibernateEnabled}
else {$he = "Key not Found"}
$hscah = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer'
if (Test-Path $hscah) {$hscah = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer").HideSCAHealth}
else {$hscah = "Key not Found"}
$ndtar = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer'
if (Test-Path $ndtar) {$ndtar = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer").NoDriveTypeAutoRun}
else {$ndtar = "Key not Found"}
$tos = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Windows\Sidebar'
if (Test-Path $tos) {$tos = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Windows\Sidebar").TurnOffSidebar}
else {$tos = "Key not Found"}
$ebt = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer\Advanced'
if (Test-Path $ebt) {$ebt = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer\Advanced").EnableBaloonTips}
else {$ebt = "Key not Found"}
$udnd = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient'
if (Test-Path $udnd) {$udnd = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient").UseDomainNameDevolution}
else {$udnd = "Key not Found"}
$dndl = 'HKLM:\SYSTEM\CURRENTCONTROLSET\SERVICES\Dnscache\Parameters'
if (Test-Path $dndl) {$dndl = (Get-ItemProperty -Path "HKLM:\SYSTEM\CURRENTCONTROLSET\SERVICES\Dnscache\Parameters").DomainNameDevolutionlevel}
else {$dndl = "Key not Found"}
$oads = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads'
if (Test-Path $oads) {$oads = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads")."*"}
else {$oads = "Key not Found"}
$ads = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads'
if (Test-Path $ads) {$ads = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\")."*"}
else {$ads = "Key not Found"}
$soc = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching'
if (Test-Path $soc) {$soc = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching").SearchOrderConfig}
else {$soc = "Key not Found"}
$narwlou = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'
if (Test-Path $narwlou) {$narwlou = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU").NoAutoRebootWithLoggedOnUsers}
else {$narwlou = "Key not Found"}
$dc = 'HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters'
if (Test-Path $dc) {$dc = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters").DisabledComponents}
else {$dc = "Key not Found"}
$atgh = 'HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance'
if (Test-Path $atgh) {$atgh = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance").fAllowToGetHelp}
else {$atgh = "Key not Found"}
$dtsc = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services'
if (Test-Path $dtsc) {$dtsc = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services").fDenyTSConnections}
else {$dtsc = "Key not Found"}
$elua = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System'
if (Test-Path $elua) {$elua = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System").EnableLUA}
else {$elua = "Key not Found"}
$ddlun = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System'
if (Test-Path $ddlun) {$ddlun = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System").dontdisplaylastusername}
else {$ddlun = "Key not Found"}
#Services
$ls = (Get-WmiObject Win32_Service -filter "Name='LanmanServer'").StartMode
$mpssvc = (Get-WmiObject Win32_Service -filter "Name='MPSSVC'").StartMode
$wd = (Get-WmiObject Win32_Service -filter "Name='WinDefend'").StartMode
$wscsvc = (Get-WmiObject Win32_Service -filter "Name='WSCSVC'").StartMode
$trkwks = (Get-WmiObject Win32_Service -filter "Name='TRKWKS'").StartMode
$napagent = (Get-WmiObject Win32_Service -filter "Name='NAPAGENT'").StartMode
$wuauserv = (Get-WmiObject Win32_Service -filter "Name='WUAUSERV'").StartMode
#Local Accounts
$Adm = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True' AND Name='Administrator'"
$Admin = $Adm.Disabled
$Gu = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True' AND Name='Guest'"
$Guest = $Gu.Disabled
#Make individual arrays from each queried information
$RegValues = #($dnc,$acu,$he,$hscah,$ndtar,$tos,$ebt,$udnd,$dndl,$oads,$ads,$soc,$narwlou,$dc,$atgh,$dtsc,$elua,$ddlun)
$ServiceValues = #($ls,$mpssvc,$wd,$wscsvc,$trkwks,$napagent,$wuauserv)
$UsersValues = #($Admin,$Guest)
#Make array of all keys
$RegAll = #($RegKeys[0], $RegValues[0],$RegKeys[1], $RegValues[1],$RegKeys[2], $RegValues[2],$RegKeys[3], $RegValues[3], $RegKeys[4], $RegValues[4], $RegKeys[5], $RegValues[5]
$RegKeys[6], $RegValues[6], $RegKeys[7], $RegValues[7], $RegKeys[8], $RegValues[8], $RegKeys[9], $RegValues[9], $RegKeys[10], $RegValues[10]
$RegKeys[11], $RegValues[11], $RegKeys[12], $RegValues[12], $RegKeys[13], $RegValues[13], $RegKeys[14], $RegValues[14], $RegKeys[15], $RegValues[15]
$RegKeys[16], $RegValues[16], $RegKeys[17], $RegValues[17], $RegKeys[18], $RegValues[18], $Services[0], $ServiceValues[0], $Services[1], $ServiceValues[1]
, $Services[2], $ServiceValues[2], $Services[3], $ServiceValues[3], $Services[4], $ServiceValues[4], $Services[5], $ServiceValues[5], $Services[6], $ServiceValues[6],
$Users[0], $UsersValues[0], $Users[1], $UsersValues[1])
#output to html
$RegAll # | Select #{label='Item';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Item' |Out-File c:\Scripts.html
This is an example which I have used in a script. You can adpt it on your script. Ask when you need help.
$YourArray = #()
#Object one for the array
$test1 = New-Object –TypeName PSObject
$test1 | Add-Member –MemberType NoteProperty –Name Propert_1 –Value "Example1"
$test1 | Add-Member –MemberType NoteProperty –Name Propert_2 –Value "Example2"
$test1 | Add-Member -MemberType NoteProperty -Name Propert_3 -Value "Example3"
#Object two for the array
$test2 = New-Object –TypeName PSObject
$test2 | Add-Member –MemberType NoteProperty –Name Propert_1 –Value "Example_2_1"
$test2 | Add-Member –MemberType NoteProperty –Name Propert_2 –Value "Example_2_2"
$test2 | Add-Member -MemberType NoteProperty -Name Propert_3 -Value "Example_2_3"
$YourArray = $test1,$test2
$beginning = {
#html code the format of the table
#'
<html>
<head>
<title>Report</title>
<STYLE type="text/css">
BODY{background-color:#b0c4de;}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{font-family:SegoeUI, sans-serif; font-size:15; border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:#778899}
TD{font-family:Consolas, sans-serif; font-size:12; border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
tr:nth-child(odd) { background-color:#d3d3d3;}
tr:nth-child(even) { background-color:white;}
</STYLE>
</head>
<h1>Stackoverflow example</h1>
<table>
<tr><th>Propert_1</th><th>Propert_2</th><th>Propert_3</th></tr>
'#
}
#Mapping between Property and table
$process = {
$Propert_1 = $_.Propert_1
$Propert_2 = $_.Propert_2
$Propert_3 = $_.Propert_3
'<tr>'
'<td bgcolor="#33CC33">{0}</td>' -f $Propert_1
'<td bgcolor="#FFFFFF">{0}</td>' -f $Propert_2
'<td bgcolor="#FFFFFF">{0}</td>' -f $Propert_3
'</tr>'
}
$end = {
#'
</table>
</html>
</body>
'#
}
#Export the array in a html sheet
$YourArray | ForEach-Object -Begin $beginning -Process $process -End $end | Out-File -FilePath "U:\Export_Report.html" -Encoding utf8
I am making a script that goes into all servers we're hosting and gets all members of a specific group and the domain name, and then exports it to a file. I'm saving the users and the domain names into two arrays AA (user array) and DA (domain array) AA stands for användararray, and "användare" is users in swedish so it makes sense to me.
I noticed that the export step didn't work, no users or domain names were exported, so I tried to print them in the function. But it doesn't print anything, so I tried to print it in a different location (didn't work). After some experimenting I came to the conlusion that the only place the arrays actually contains any information is inside the foreach loop where I save the users that I find??!
Here is the code
unction GetData([int]$p) {
Write-Host("B")
for ($row = 1; $row -le $UsernamesArray.Length; $row++)
{
if($CloudArray[$row] -eq 1)
{
.
$secstr = New-Object -TypeName System.Security.SecureString
$PasswordsArray[$row].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UsernamesArray[$row], $secstr
$output = Invoke-Command -computername $AddressArray[$row] -credential $cred -ScriptBlock {
Import-Module Activedirectory
foreach ($Anvandare in (Get-ADGroupMember fjärrskrivbordsanvändare))
{
$AA = #($Anvandare.Name)
$DA = gc env:UserDomain
#$DA + ";" + $Anvandare.Name
$DA + ";" + $AA
}
}
$output
}
}
$DA
$AA
}
function Export {
Write-Host("C")
$filsökväg = "C:\Users\322sien\Desktop\Coolkids.csv"
$ColForetag = "Företag"
$ColAnvandare = "Användare"
$Emptyline = "`n"
$delimiter = ";"
for ($p = 1; $p -le $DomainArray.Length; $p++) {
$ColForetag + $delimiter + $ColAnvandare | Out-File $filsökväg
$DA + $delimiter + $AA | Out-File $filsökväg -Append
}
}
ReadInfo
GetData
Export
Can anyone help me with this? I've sat down with this all day and i cant find a solution.
Your variables $DA and $AA are bound to GetData function, so they live only there. You could make them available inside your script by changing it's scope.
Change this:
$AA = #($Anvandare.Name)
$DA = gc env:UserDomain
To this:
$script:AA = #($Anvandare.Name)
$script:DA = gc env:UserDomain
So they will now be available for other functions inside the script.
Also I found the ways to improve your script, hope you can see the logic:
function GetData([int]$p) {
Write-Host("B")
for ($row = 1; $row -le $UsernamesArray.Length; $row++)
{
if($CloudArray[$row] -eq 1)
{
.
$secstr = New-Object -TypeName System.Security.SecureString
$PasswordsArray[$row].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UsernamesArray[$row], $secstr
[array]$output = Invoke-Command -computername $AddressArray[$row] -credential $cred -ScriptBlock {
Import-Module Activedirectory
$array = #()
foreach ($Anvandare in (Get-ADGroupMember fjärrskrivbordsanvändare))
{
$object = New-Object PSObject
$object | Add-Member -MemberType NoteProperty -Name AA -Value #($Anvandare.Name)
$object | Add-Member -MemberType NoteProperty -Name DA -Value (gc env:UserDomain)
$object | Add-Member -MemberType NoteProperty -Name Something -Value $DA + ";" + $AA
$array += $object
}
Write-Output $array
}
Write-Output $output
}
}
}
Your function will now output some data.