Why is my object array doubling results? - arrays

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
}

Related

New-Object : Cannot bind parameter 'Property'. Cannot convert the "" value of type PSCustomObject to type IDictionary

I'm having a hard time converting results from Invoke-SqlCmd to a PSCustomobject.
So, I input my query and SQL server, then I run the Invoke-SqlCmd function, and then I try to add data from that (the database logical name, and the autogrowth status) to my PSCustomobject, so I can return it back to my modules public function.
$sqlinstance = "---"
$query = "---"
if ($sqlInstance -match "---") {
$dbAutogrowIGP = Invoke-Sqlcmd -Query $query -ServerInstance $sqlInstance
if ($dbAutogrowIGP.Growth -gt 100 -and $dbAutogrowIGP.Growth -lt 500) {
$autogrowStatus = [PSCustomObject]#{
'SQL_Instance' = $dbAutogrowIGP.LogicalName
'Check' = "Autogrow"
'Status' = "green"
'Status_reason' = ""
}
New-Object -Type Dictionary -Property $autogrowStatus
}
foreach ($db in $dbAutogrowIGP) {
if ($db.Growth -lt 100 -or $db.Growth -gt 500 -and $db.Growth -notlike "%") {
$autogrowStatus = [PSCustomObject]#{
'SQL_Instance' = $db.LogicalName
'Check' = "Autogrow"
'Status' = "red"
'Status_reason' = "$($db.LogicalName) has autogrowth set to $($db.Growth)."
}
New-Object -Type Dictionary -Property $autogrowStatus
}
if ($db.Growth -like "%") {
$autogrowStatus = [PSCustomObject]#{
'SQL_Instance' = $db.LogicalName
'Check' = "Autogrow"
'Status' = "yellow"
'Status_reason' = "$($db.LogicalName) has autogrowth set percentually, it should be an absolute number."
}
New-Object -Type Dictionary -Property $autogrowStatus
}
}
}
return $autogrowStatus
I've debugged it, and I've noticed it fails on the New-object call. I've tried both Dictionary and PSObject/PSCustomObject - however neither works
In my other functions, this works as expected, however in those, I'm using dbatools to make a call.
$getLogSizeIGP = Get-DbaDbLogSpace -sqlInstance $sqlInstance
if ($getLogSizeIGP.LogSize.Gigabyte -lt 10 -and $getLogSizeIGP.LogSpaceUsedPercent -lt 50) {
$logStatus = #{
'SQL_Instance' = $getLogSizeIGP.SqlInstance
'Check' = "Log_size"
'Status' = [gmEnvStatuses]::green
'Status_reason' = ""
}
New-Object -Type PSObject -Property $logStatus
}
How would I go about solving this issue?
This is the whole error message:
New-Object : Cannot bind parameter 'Property'. Cannot convert the "#{SQL_Instance=Maintenance_log; Check=Autogrow; Status=red; Status_reason=Maintenance_log has autogrowth set to 10%.}" value of type "System.Management.Automation.PSCustomObject" to type
"System.Collections.IDictionary".
At C:\Users\---\Desktop\autogrowth.ps1:50 char:55
+ New-Object -Type Dictionary -Property $autogrowStatus
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewObjectCommand
Thanks!
The easiest way of collecting this data is by capturing it all at the beginning of the if ($sqlInstance -match "---") { statement and simply output the PsCustomObjects without trying to convert them.
Something like
$sqlinstance = "---"
$query = "---"
$autogrowStatus = if ($sqlInstance -match "---") {
$dbAutogrowIGP = Invoke-Sqlcmd -Query $query -ServerInstance $sqlInstance
if ($dbAutogrowIGP.Growth -gt 100 -and $dbAutogrowIGP.Growth -lt 500) {
# output the object to be captured in the $autogrowStatus variable
[PSCustomObject]#{
'SQL_Instance' = $dbAutogrowIGP.LogicalName
'Check' = "Autogrow"
'Status' = "green"
'Status_reason' = ""
}
}
foreach ($db in $dbAutogrowIGP) {
if ($db.Growth -lt 100 -or $db.Growth -gt 500 -and $db.Growth -notlike "%") {
[PSCustomObject]#{
'SQL_Instance' = $db.LogicalName
'Check' = "Autogrow"
'Status' = "red"
'Status_reason' = "$($db.LogicalName) has autogrowth set to $($db.Growth)."
}
}
if ($db.Growth -like "%") {
[PSCustomObject]#{
'SQL_Instance' = $db.LogicalName
'Check' = "Autogrow"
'Status' = "yellow"
'Status_reason' = "$($db.LogicalName) has autogrowth set percentually, it should be an absolute number."
}
}
}
}
return $autogrowStatus
The variable $autogrowStatus will become an array of PSCustomObjects to handle in the rest of your functions.
Hope this helps

Find duplicate values in an array

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
}

Can't use Get-ADGroup in foreach loop

I want to use a Get-ADGroup command in nested foreach loops. But somehow the command results nothing back. The command and filters are corect, as you can see it at the very bottom after the loops, the same instruction works there perfectly, for whatever reason.
$file = "\\path"
$data = Import-Csv $file -Delimiter ";" -Encoding UTF7 |
select -First 5
Measure-Command {
foreach ($item in $data ) {
$tiefe = $($item.'Tiefe')
$pfad = $($item.'Pfad')
$recht = $($item.'Recht')
$trustee = $($item.'trustee')
$LDAPDirectoryService = 'IP-Adresss'
$DomainDN = 'o=enterprise'
$LDAPFilter = "cn=$trustee"
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')
$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer = $false
$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = #('*')
$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList
$groups = $LDAPServer.SendRequest($SearchRequest)
$groups
#Prüft ob Gruppe existiert
if ($groups.Entries.Count -eq 0) {
Write-Host " Group not found!" `n -Foregroundcolor Red $LDAPFilter
#Speichert alle nicht gefundenen Gruppen zur manuellen Nachbearbeitung
Add-Content -Path \\Path -Value "$LDAPFilter"
}
foreach ($group in $groups.Entries) {
#Listet alle Member der oben übergebenen Gruppe auf
$users = $group.Attributes['member'].GetValues('string')
foreach ($user in $users) {
Write-Host $user
#Hier den User zur AD Gruppe hinzufügen
Write-Host "user zur Gruppe hinzufügen $pfad-$recht" -ForegroundColor Red
# This little Boy doesnt work
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' |
where {$_.Description -like "*$pfad" -and $_.Name.EndsWith($recht)}
#Add-ADGroupMember -Identity S-1-5-21-219376080-2991882224-574971396-34759 -Members $user -Whatif
}
}
}
}
# Here the command works without a fault
Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' |
where {$_.Description -like "*$pfad" -and $_.Name.EndsWith($recht)}
I still dont know why but I found a solution working for me.
$AD = Get-ADGroup -Properties Name, Description -Filter 'Name -like "F-KT-*"' | where {$_.Description -like "*$pfad" -and $_.Name.endswith($recht) }
write-Host $AD.Name -ForegroundColor Yellow
Maybe someone can tell me why I have to declare get-ADGroup as a variable in the Loop, but outside its working without it.

Powershell Script Limiting OU search for Active/Disabled users

I currently have a script that is functional with the exception of two search features. The Active user search which is limited to two OUs, and the Disabled user which is limited to a separate 2 OUs. This is all contained within a while loop that performs a search of all of AD. I am having difficulty getting these two sub-searches to work. They return the result of all of AD users no matter what. I have several different renditions in the Disabled search.
I am trying to get it to search the specific OU for user, if not present, display message saying user not found.
#Requires -Version 2.0
#Connection and Startup Strings
cls
Import-Module ActiveDirectory
if ( (Get-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue) -eq $null ){
Add-PSSnapin Quest.ActiveRoles.ADManagement
}
#-Set Window title
$host.UI.RawUI.WindowTitle = $MyInvocation.MyCommand.Name + " - " + (Get-Item $MyInvocation.MyCommand.Path).LastWriteTime.ToString("yyyy-MM-dd_HH:mm:ss")
#Requires -Version 2.0
$ADServer = 'childDomain.domain.com'
$Aous = 'OU=Users,OU=Production,DC=childdomain,DC=domain,DC=com','OU=Onboarding,OU=Production,DC=childdomain,DC=domain,DC=com'
$Dous = 'OU=Terminated,DC=childdomain,DC=domain,DC=com', 'OU=Disability Leave,OU=Production,DC=childdomain,DC=domain,DC=com'
$ADous = 'OU=Users,OU=Production,DC=childdomain,DC=domain,DC=com','OU=Onboarding,OU=Production,DC=childdomain,DC=domain,DC=com','OU=Terminated,DC=childdomain,DC=domain,DC=com', 'OU=Disability Leave,OU=Production,DC=childdomain,DC=domain,DC=com'
$Exportpath = "C:\domain\ExportADUsers\"
if(!(test-path $Exportpath)){ New-Item -ItemType Directory -Force -Path $Exportpath }
$Logfile = "C:\domain\UserSearch_errors.txt"
#-determine Service Desk agent; used in Signature as well as Push-Button
if($env:UserName -Match "x_\w.*"){ $SDAgent = $env:UserName.Substring(2) }
else{ $SDAgent = $env:UserName }
#--Prompt/menu strings
$noADuserErrorString = "`n---..-- No Account found in Active Directory --..---"
$promptActiveSearchString = " - Enter the employee username that you wish to search the Active OU's for"
$promptDisabledSearchString = " - Enter the employee username that you wish to search the Disabled OU's for"
$emptyInput = "No entry specified, please retype request."
$cancelOnboardForm = "Exiting Onboarding form. No actions taken."
$script:TESTING = $False
function testing-message
{
Write-Host "script:TESTING is currently : " -NoNewline
if($script:TESTING){ Write-Host "TRUE" -ForegroundColor Red }
else { Write-Host "FALSE" -ForegroundColor Green }
}
Connect-QADService childdomain.domain.com
Write-Host "`n`n**********************`n**`n** " -NoNewline -ForegroundColor Green
Write-Host "Welcome, $SDAgent ($env:UserName)"
Write-Host "**`n********`n" -ForegroundColor Green
$SelectString = "Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container}}, homeDirectory"
function SelectStandard
{
#-trying to create function to standardize output for various search modes
Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container}}, homeDirectory
}
function Show-Error
{
#- NOTE: add "-ErrorAction Stop" switch to force terminating error
Write-Host " |====================="
Write-Host " |"
Write-Host " | " -NoNewline
Write-Host "Caught an exception:" -ForegroundColor Red
Write-Host " | " -NoNewline
Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " | " -NoNewline
Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " | " -NoNewline
Write-Host "Exception Error[0]: $($error[0])" -ForegroundColor Red
Write-Host " |"
Write-Host " |====================="
}
function Show-Prompt
{
$prompttime = Get-Date -format T
$prompttime = Get-Date -format hh:mm:ss
Write-Host " `n<" -NoNewline
Write-Host "$prompttime" -ForegroundColor Yellow -BackgroundColor Black -NoNewline
Write-Host ">" -NoNewline
Write-Host " Enter the username you would like to lookup: " -ForegroundColor Cyan -BackgroundColor Black -NoNewline
# Write-Host " `n[ $prompttime ] Enter the username you would like to lookup: " -ForegroundColor Cyan -NoNewline
}
##########################
# main loop
while($true){
Show-Prompt
$username = Read-Host
$username = $username.Trim()
#-ignore blank
elseif (($username -Match "^\s+$") -or ($username -eq '')){
Write-Host $emptyInput
Continue
}
#-Search Active OU's
#WIP
elseif ($username -eq 'Active'){
$usra = Read-Host -prompt $promptActiveSearchString
$usra = $usra.Trim()
$activecorp = Get-QADUser $usra -Searchroot $aous | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container} }
$activecorp
if (!$activecorp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }
$username = $usra #~why?
Continue
}
#-Search Terminated & Disability Leave OU's
#WIP
elseif ($username -eq 'Disabled'){
$usra = Read-Host -prompt $promptDisabledSearchString
$usra = $usra.Trim()
$validUsername = $False
try{
Get-ADUser -Server $ADServer -Searchbase $Dous | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container} }
$validUsername = $True
}
catch{
Write-Host "$usra $noADuserErrorString" -ForegroundColor Red -BackgroundColor Black
$validUsername = $False
}
$username = $usra
<#
$usra = Read-Host -prompt $promptDisabledSearchString
$usra = $usra.Trim()
$discorp = Get-QADUser $usra -Searchroot $dous | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container} }
if (!$discorp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }
#$username = $usra #~why?
Return $discorp
#Continue
foreach($AllADUsers in $ADous){Get-ADUser -server $ADServer `
-SearchBase $AllADUsers `
-Filter * -Properties * |
#>
}
#-if starts with a number, assume phone number mode
elseif ($username -Match "^\d.*"){
$phoneno = $username
# Connect-QADService childdomain.domain.com
$phonecorp = Get-QADUser -Enabled -telephonenumber "*$phoneno" | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container} }
$phonecorp
if (!$phonecorp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }
Continue
}
#-Get employee ID
elseif ($username -eq 'gid'){
$usra = Read-Host -prompt " - Enter the employee username that you wish to get the Employee ID for"
$usra = $usra.Trim()
$validUsername = $False
try{
Get-ADUser $usra -Properties EmployeeID | Select EmployeeID
$validUsername = $True
}
catch{
Write-Host "[$usra] is not a valid username. Username must match EXACTLY." -ForegroundColor Red -BackgroundColor Black
$validUsername = $False
}
$username = $usra
}
#-Exit script gracefully
elseif ($username -eq 'Exit'){
Exit
}
#-perform basic search
else{
# Write-Host "`n - basic search - " #-for testing, to verify elseif as well as to prove Active/Disabled options are not working as intended
# Connect-QADService childdomain.domain.com
$corp = Get-QADUser $username | Select Domain, Displayname, Description, AccountExpires, PasswordLastSet, Lastlogon, AccountIsDisabled, AccountIsLockedOut, PasswordNeverExpires, UserMustChangePassword, AccountIsExpired, PasswordIsExpired, AccountExpirationStatus, UserPrincipalName, #{l='DN'; e={Find-Container}}, homeDirectory, #{n="ManagerName";e={(Get-ADUser -Identity $_.Manager -properties DisplayName).DisplayName}}
$corp
if (!$corp) { Write-Host $noADuserErrorString -ForegroundColor Red -BackgroundColor Black }
}
}
I'm not entirely clear on what you're trying to do, but I do see a couple problems in your code.
I can't speak to the Quest cmdlets, but I can speak to Get-ADUser.
The SearchBase parameter takes a sting, but you've declared $Dous as an array:
$Dous = 'OU=Terminated,DC=childdomain,DC=domain,DC=com', 'OU=Disability Leave,OU=Production,DC=childdomain,DC=domain,DC=com'
Then passed it to Get-ADUser:
Get-ADUser -Server $ADServer -Searchbase $Dous
That's not going to work. You need to run Get-ADUser once for each OU.
You also need to set the Filter parameter, even if you just set it to * to get every user:
Get-ADUser -Filter * -Server $ADServer -Searchbase 'OU=Terminated,DC=childdomain,DC=domain,DC=com'
But you may want to set Filter differently if you know the name of the account you're looking for.

Upload file from my local system on Sharepoint

Please help me with the complete batch file code:
I want to upload file(.xls,csv) onto Sharepoint server using batch file. It should perform:
a> Do a check to see in the sharepoint location if the file exist. If exist then do nothing.
b> If the file do not exist, then
1.check the local if the file is present in this location or not. If yes then simply upload it n sharepoint.
2.Step a. again
This batch file will be triggered by windows schedular every 20 mins.
My goal is to upload the files the moment they get generated.
Request you to please help me with the correct code logic which I can implement.
Thankyou for the help n support!
Take a look of the SharePoint Multiple File Upload Script;
function Copy-FilestoSP
{
Param (
[parameter(Mandatory=$true)][string]$LocalPath,
[parameter(Mandatory=$true)][string]$SiteUrl,
[parameter(Mandatory=$true)][string]$Library,
[parameter(Mandatory=$false)][string]$LibraryStartFolder,
[parameter(Mandatory=$false)][string]$ManifestFilePath,
[parameter(Mandatory=$false)][switch]$IncludeSubFolders,
[parameter(Mandatory=$false)][switch]$Approve,
[parameter(Mandatory=$false)][switch]$CheckIn,
[parameter(Mandatory=$false)][switch]$Overwrite,
[parameter(Mandatory=$false)][switch]$FlattenStructure
)
try
{
#Get web and document library objects
$web = Get-SPWeb $SiteUrl
$docLibrary = $web.Lists[$Library]
#Load metadata manifest file, if specified
if ($PSBoundParameters.ContainsKey('ManifestFilePath')) {
$metadataManifest = [xml] (Get-Content ($ManifestFilePath))
}
else
{
write-host "Manifest file not specified for categorising uploaded documents"
}
#Check for the LibraryStartFolder parameter to specify a root folder
if ($PSBoundParameters.ContainsKey('LibraryStartFolder')) {
$folder = $web.GetFolder($docLibrary.Title + $LibraryStartFolder)
}
else
{
$folder = $docLibrary.RootFolder
}
#Attach to local folder and enumerate through all files
if($IncludeSubFolders) {
$files = Get-ChildItem $LocalPath -Recurse
}
else
{
$files = Get-ChildItem $LocalPath
}
$files | ForEach-Object {
#Check if the object is a folder - if so, create it in doc library
if ($_.PSIsContainer) {
if (($IncludeSubFolders) -and (!$FlattenStructure)) {
#Generate folder path for creation in SharePoint
#by looking at the parent folder on the local path
$spFolderPath = ($_.Parent.FullName.Replace($LocalPath,"")).Replace("\","/")
#Get the folder into which the new folder will be created
#by adding the folder path generated above, if one existed
if ($spFolderPath -eq "") {
$currentFolder = $web.GetFolder($folder.Url)
}
else
{
$currentFolder = $web.GetFolder($folder.Url + $spFolderPath)
}
#Check to see if subfolder already exists
#and create it if not
$testFolder = $currentFolder.SubFolders[$_.Name]
if ($testFolder -eq $null) {
write-host "`nAdding folder" $_.Name "to" $docLibrary.Title "in" $web.Title "..." -foregroundcolor Green
$newFolder = $currentFolder.SubFolders.Add($_.Name)
}
else
{
write-host "`nFolder" $_.Name "already exists in" $docLibrary.Title "and shall not be created" -foregroundcolor Red
}
}
}
else
{
#Generate file path for upload into SharePoint
if ($FlattenStructure) {
$spFilePath = ("/" + $_.Name)
}
else
{
$spFilePath = ($_.FullName.Replace($LocalPath,"")).Replace("\","/")
}
$spFullPath = $folder.Url + $spFilePath
#Check if the file exists and the overwrite option is selected before adding the file
if ((!$web.GetFile($spFullPath).Exists) -or ($Overwrite)) {
#Add file
write-host "`nCopying" $_.Name "to" $spFullPath.Replace("/" + $_.Name,"") "in" $web.Title "..." -foregroundcolor Green
$spFile = $folder.Files.Add($spFullPath, $_.OpenRead(), $true)
$spItem = $spFile.Item
#Walk through manifest XML file and configure column values on the file
$metadataManifest.Columns.Column | ForEach-Object {
#Single value text columns
try
{
if (($_.Type -eq "Text") -or
($_.Type -eq "Choice") -or
($_.Type -eq "Boolean") -or
($_.Type -eq "Number") -or
($_.Type -eq "Currency")) {
$columnName = $_.Name
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
$_.Values.Value | ForEach-Object {
$spItem[$columnName] = $_
write-host "Value set to"$_
}
}
}
catch {}
#Multiple line text column
try
{
if ($_.Type -eq "Note") {
$columnName = $_.Name
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
[string]$multiLineValue = $null
$_.Values.Value | ForEach-Object {
$multiLineValue = $multiLineValue + $_ + "`n"
}
$spItem[$columnName] = $multiLineValue
write-host "Value on multiiple line text column set"
}
}
catch {}
#Multiple choice columns
try
{
if ($_.Type -eq "MultiChoice") {
$columnName = $_.Name
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
[string]$multiChoiceValue = ";#"
$_.Values.Value | ForEach-Object {
$multiChoiceValue = $multiChoiceValue + $_ + ";#"
write-host "Value"$_ "added to column"
}
$spItem[$columnName] = $multiChoiceValue
}
}
catch {}
#Hyperlink columns
try
{
if ($_.Type -eq "URL") {
$columnName = $_.Name
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
$urlFieldValue = New-Object Microsoft.SharePoint.SPFieldUrlValue
$_.Values.Description | ForEach-Object {
$urlFieldValue.Description = $_
}
$_.Values.Value | ForEach-Object {
$urlFieldValue.Url = $_
}
$spItem[$columnName] = $urlFieldValue
write-host "Value set to"$urlFieldValue.Url
}
}
catch {}
#Single User column
try
{
if ($_.Type -eq "User") {
$columnName = $_.Name
$user = $null
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
$_.Values.Value | ForEach-Object {
#Check to see if SharePoint group exists in the site collection
if ($web.SiteGroups[$_])
{
#Set account variable to SPGroup
$account = $web.SiteGroups[$_]
}
else
{
#Set account variable to SPUser
$account = $web.EnsureUser($_)
}
$spItem[$columnName] = $account
write-host "Value set to"$_
}
}
}
catch {}
#Multiple User column
try
{
if ($_.Type -eq "UserMulti") {
$columnName = $_.Name
$user = $null
$userField = New-Object Microsoft.SharePoint.SPFieldUserValueCollection
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
$_.Values.Value | ForEach-Object {
#Check to see if SharePoint group exists in the site collection
if ($web.SiteGroups[$_])
{
#Set account variable to SPGroup
$account = $web.SiteGroups[$_]
}
else
{
#Set account variable to SPUser
$account = $web.EnsureUser($_)
}
$userValue = New-Object Microsoft.SharePoint.SPFieldUserValue($web, $account.ID, $account.Name)
$userField.Add($userValue)
write-host "Value"$_ "added to column"
}
$spItem[$columnName] = $userField
}
}
catch {}
#Single value Managed Metadata column
try
{
if ($_.Type -eq "TaxonomyFieldType") {
$columnName = $_.Name
$taxonomySession = Get-SPTaxonomySession -Site $web.Site
$termStore = $taxonomySession.DefaultSiteCollectionTermStore
$taxonomyField = $docLibrary.Fields[$columnName]
$termSet = $termStore.GetTermSet($taxonomyField.TermSetId)
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
$_.Values.Value | ForEach-Object {
$termCollection = $termSet.GetTerms($_, $true)
if ($termCollection.Count -eq 0)
{
$term = $termSet.CreateTerm($_, 1033)
$termStore.CommitAll()
}
else
{
$term = $termCollection[0]
}
$taxonomyField.SetFieldValue($spItem, $term)
write-host "Value set to"$_
}
}
}
catch {}
#Multi value Managed Metadata column
try
{
if ($_.Type -eq "TaxonomyFieldTypeMulti") {
$columnName = $_.Name
$taxonomySession = Get-SPTaxonomySession -Site $web.Site
$termStore = $taxonomySession.DefaultSiteCollectionTermStore
$taxonomyField = $docLibrary.Fields[$columnName]
$tfvc = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection($taxonomyField)
$termSet = $termStore.GetTermSet($taxonomyField.TermSetId)
write-host "Setting value on column"$columnName "..." -foregroundcolor Blue
$_.Values.Value | ForEach-Object {
$termCollection = $termSet.GetTerms($_, $true)
if ($termCollection.Count -eq 0)
{
$term = $termSet.CreateTerm($_, 1033)
$termStore.CommitAll()
}
else
{
$term = $termCollection[0]
}
$valueString = "-1;#" + $term.Name + "|" + $term.Id.ToString()
$taxonomyValue = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($valueString)
$tfvc.Add($taxonomyValue)
write-host "Value"$_ "added to column"
}
$taxonomyField.SetFieldValue($spItem, $tfvc)
}
}
catch {}
#Update document with new column values
$spItem.SystemUpdate($false)
}
#Check in file to document library (if required)
#MinorCheckIn=0, MajorCheckIn=1, OverwriteCheckIn=2
if ($CheckIn) {
if ($spFile.CheckOutStatus -ne "None") {
$spFile.CheckIn("File copied from " + $filePath, 1)
write-host $spfile.Name"checked in"
}
}
#Approve file (if required)
if ($Approve) {
if ($spItem.ListItems.List.EnableModeration -eq $true) {
$spFile.Approve("File automatically approved after copying from " + $filePath)
if ($spItem["Approval Status"] -eq 0) { write-host $spfile.Name"approved" }
}
}
}
else
{
write-host "`nFile"$_.Name "already exists in" $spFullPath.Replace("/" + $_.Name,"") "and shall not be uploaded" -foregroundcolor Red
}
}
}
}
catch [System.SystemException]
{
write-host "The script has stopped because there has been an error. "$_.Message
}
finally
{
$web.Dispose()
}
}
write-host "SharePoint 2010 Multiple File Upload Script - Get-SPScripts.com"
More information is available in CodePlex; http://spfileupload.codeplex.com/SourceControl/latest#Get-SPScripts.Copy-FilesToSP.ps1

Resources