Powershell export-csv SQL User rights - sql-server

sorry for the question but i have a problem to export to csv.
I found this useful script to have all userrights on the databases but I dont know how to export it to csv like: SQL Instance, Login, Permissions
I tried with write-output but nothing good.
Thanks ins advance for your help
Function GetDBUserInfo($Dbase)
{
if ($dbase.status -eq "Normal")
{$users = $Dbase.users | where {$_.login -eq $SQLLogin.name}
foreach ($u in $users)
{
if ($u)
{
$DBRoles = $u.enumroles()
foreach ($role in $DBRoles) {
if ($role -eq "db_owner") {
write-host $role "on"$Dbase.name -foregroundcolor "red"
}
else {
write-host $role "on"$Dbase.name
}
}
foreach($perm in $Dbase.EnumObjectPermissions($u.Name)){
write-host $perm.permissionstate $perm.permissiontype "on" $perm.objectname "in" $DBase.name }
}
}
}
}
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
foreach ($SQLsvr in get-content "path to instace list")
{
$svr = new-object ("Microsoft.SqlServer.Management.Smo.Server") $SQLsvr
write-host "=============================================================================="
$svr.name
$SQLLogins = $svr.logins
foreach ($SQLLogin in $SQLLogins)
{
write-host "Login : " $SQLLogin.name
if ($SQLLogin.EnumDatabaseMappings())
{write-host "Permissions:"
foreach ( $DB in $svr.Databases)
{
GetDBUserInfo($DB)
}
}
Else
{write-host "Permissions: None"
}
write-host "--------------------------------------------------------------------------------"
}
}

Related

Invoke-SqlCmd generates an exception in foreach loop?

I am running 2 different sql query one after the other to get the details from database using Invoke-Sqlcmd but getting an exception.
The WriteObject and WriteError methods cannot be called from outside the overrides of the BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread. Validate that the cmdlet makes these calls correctly
Script:
$ok = "true"
$serverName = $env:COMPUTERNAME
$query1 = "SELECT * FROM sys.server_audits WHERE name = 'Login'"
$query2 = "SELECT * FROM sys.dm_server_audit_status WHERE name = 'Login' AND status_desc = 'STARTED'"
try
{
Write-Host "Getting running Sql Server Instance (online)"
$sqlInstances = (Get-Service -Name MSSQL$* | Where-Object { $_.status -eq "Running" }).Name
$sqlInstancesCount = $sqlInstances.Count
Write-Host $eventID "$sqlInstancesCount Sql Server Instance found"
if($sqlInstancesCount)
{
foreach($item in $sqlInstances)
{
$count = 0
$instanceName = $item -replace "MSSQL\$", ""
$sqlInstanceFullname = Join-Path -Path $serverName -ChildPath "\" | Join-Path -ChildPath $instanceName
Write-Host "Sql Server instance fullname - $sqlInstanceFullname"
while($count -lt 3)
{
Write-Host "Clear existing connection."
[System.Data.SqlClient.SqlConnection]::ClearAllPools()
Write-Host "Executing query - $query1"
$result1 = (Invoke-Sqlcmd -Query $query1 -ServerInstance $sqlInstanceFullname)
Start-Sleep -Seconds 30
Write-Host "Clear existing connection."
[System.Data.SqlClient.SqlConnection]::ClearAllPools()
Write-Host "Executing query - $query2"
$result2 = (Invoke-Sqlcmd -Query $query2 -ServerInstance $sqlInstanceFullname)
if($null -eq $result1)
{
$message = "$serverName - The SQL Server [Login] does not exist."
$ok = "false"
$count = $count + 1
}
elseif($null -eq $result2)
{
$message = "$serverName - The SQL Server [Login] is disabled."
$ok = "false"
$count = $count + 1
}
else
{
$message = "SQL Login is enabled and running."
$count = 3
$ok = "true"
}
}
}
}
else
{
$ok = "false"
throw "$serverName - SQL Server Instances might be offline or not exist!"
}
}
catch
{
throw $_
}
I have tried enclosing Invoke-Sqlcmd in brackets but still getting same exception so is there a way to remove existing thread or close the connection before executing another query.

Array returned has an unexpected element in Powershell

An array returned from a function has an unexpected element appended to it, and I cannot understand how to fix it. A help will be so much appreciated.
The array in function A, for some unknown reason is different to the array in function B that calls the function A.
function functionA(...)
{
[...]
$status = (,#("reserved",$proj,$id));
Write-Host "Status in FunctionA to FunctionB: "$status
[...]
return $status
}
I get from the Write-Host above: Status in FunctionA to FunctionB: reserved B hfuhfkhec8u8b7hf4smeu43gn4
function functionB(...)
{
[...]
$funcA = functionA
Write-Host "Status in FunctionB from FunctionA: "$funcA
[...]
}
I get from the Write-Host above: Status in FunctionB from FunctionA: 1 reserved B hfuhfkhec8u8b7hf4smeu43gn4. You can observe the $status in functionA has not the value 1, so why I get the value 1 appended in the array? What may I do to fix it?
Please check the complete code bellow, where FunctionA is CheckReservation and FunctionB is PeriodicCheckIn
PS: I noted that if I comment the function InformationMsgBox to do not call if in CheckReservation, then the code works.
function CheckReservation($headers){
$events = GetCalendarEvents($headers)
$users = Get-IniFile ..\ini\Users.ini
$user = $users.$env:UserName.email
$error = "There is not any confirmed reservation for this machine."; $status = (,#("NoReservations",$error));
$calendarId = Get-IniFile ..\ini\Computers.ini
$calendarId = $calendarId.$env:Computername.calendarId
foreach($item in $events.items)
{
if($item.status -match "confirmed")
{
$attender = $item.attendees.email |
Where-Object {$_ -contains $user}
$calendar = $item.attendees |
Where-Object {$_.email -contains $calendarId}
$calendarEmail = $calendar.email
$calendarStatus = $calendar.responseStatus
$organizer = $item.organizer.email | Where-Object {$_ -contains $user}
if(($attender -match $user) -or ($item.organizer.email -match $user))
{
if(($calendarStatus -match "accepted") -or ($item.organizer.email -match $calendarId))
{
$current = [Xml.XmlConvert]::ToString((get-date),[Xml.XmlDateTimeSerializationMode]::Local)
if(((get-date $current) -ge (get-date $item.start.dateTime)) -and ((get-date
$current) -lt (get-date $item.end.dateTime)))
{
$timespan = NEW-TIMESPAN –Start (get-date $current) –End (get-date $item.end.dateTime);
$timeexpire = [int]$timespan.TotalMinutes;
Write-Host "Minutes to expire reservation: "$timeexpire;
$Timers = Get-IniFile ..\ini\Timers.ini;
$WarningBeforeExp = $Timers.Timers.WarningBeforeExp_min;
if($timeexpire -le $WarningBeforeExp)
{
$msg = message(21);
Write-Host $msg;
InformationMsgBox $msg 10;
}
$proj=$item.summary
$id=$item.id
$status = (,#("reserved",$proj,$id));
Write-Host "Status in FunctionA to FunctionB: "$status
} else { $msg = "Reservation expired or schedule time mismatch."; $status = (,#("outOfTime",$msg)); }
}
} else { $msg = "You are not an attender for the current reservation for this machine."; $status = (,#("IsNotAttender",$msg));}
} else { $msg = "There is not any confirmed reservation for this machine. You can use it until someone makes a reservation."; $status = (,#("NoReservations",$msg));}
}
return $status
}
function PeriodicCheckIn ($OAuth2){
$checkin = $false
$Timers = Get-IniFile ..\ini\Timers.ini
$CheckInPeriodicity = $Timers.Timers.CheckInPeriodicity_min
for($i=1;;$i++)
{
$timeout = IdleTimeout
if(-not $timeout)
{
$funcA = CheckReservation $OAuth2
Write-Host "Status in FunctionB from FunctionA: "$funcA
$reservation = $funcA
if ($reservation[0] -match "reserved")
{
$project = $reservation[1]
$id = $reservation[2]
Write-Host "Reservation found"
Write-Host "Project: "$project
Write-Host "Id: "$id
if(-not $checkin)
{
storageData "CheckInOut" $OAuth2 "CheckIn" $project "" $false
$checkin = $true
$msg = message(15)
Write-Host $msg
InformationMsgBox $msg -1
}
else
{
storageData "updatetime" $OAuth2 "LastUpdate" $project "" $false
}
}
elseif($i -eq 1)
{
Write-Host "Reservation not found"
$Availability = CheckAvailability $OAuth2 "10"
Write-Host "Availability for now: "$Availability
if($Availability -match "Yes")
{
$msg = message(16)
$msgBoxInput = QuestionMsgBox $msg 30
if($msgBoxInput -eq 6)
{
$project = GetProject "FromUser"
CreateReservation $OAuth2 $project "10"
storageData "CheckInOut" $OAuth2 "CheckIn" $project "" $false
$checkin = $true
$msg = message(15)
Write-Host $msg
InformationMsgBox $msg -1
}
else
{
$leave = $true;
}
} else
{
$leave = $true;
}
}
else
{
Write-Host "O pau é aqui?1 $reservation[1]"
$msg = message(18, $reservation[1]);
Write-Host "O pau é aqui?2 $reservation[1]"
StopMsgBox $msg -60
$leave = $true;
}
} else {$leave = $true;}
if($leave -eq $true){ return $true}
Write-Host "CheckIn $i"
start-sleep -Seconds ([double]$CheckInPeriodicity*60)
}
}
function message($index,$txt){
$LastWarning_min = Get-IniFile ..\ini\Timers.ini
$LastWarning_min = $LastWarning_min.Timers.LastWarning_min/60
$ManualAuthTimeout_min = $LastWarning_min.Timers.ManualAuthTimeout_min
Write-Host "Next message index: $index"
$arrMessage =
"[MSG000] It is not possible to identify if this current PC is Workstation or Buildstation machine.",
"[MSG001] Shutting down the system.",
"[MSG002] You do not have approriate access to this function. Get in contact with lab support.",
"[MSG003] An error occurred. Verify if there are at least two not empty .txt file, if the path is correct or if you have write permission to the path $txt.",
"[MSG004] Attempt to delete a folder that does not exist: $txt.",
"[MSG005] Mapping failed. Make sure your connection can reach the networking that remote path ""$txt"" belongs.",
"[MSG006] Team not specified for the user $env:UserName. Please make sure the user is registered.",
"[MSG007] Connection failed. Make sure the PC can reach FIATAUTO networking then try again.",
"[MSG008] Error while Import-Module.",
"[MSG009] Error on OAuth 2.0 for Google APIs Authorization.",
"[MSG010] Error on Method: spreadsheets.values.get (writing) for Google Sheets API request.",
"[MSG011] Error on Method: spreadsheets.values.get (reading) for Google Sheets API request.",
"[MSG012] Error on Method: scripts.run for Google App Script API request.",
"[MSG013] Error on Events: get for Google Calendar API request.",
"[MSG014] Error on Events: list for Google Calendar API request.",
"[MSG015] Your access has been granted to work on the project: $global:project.",
"[MSG016] No reservation was found. Would you like to make a short reservation?",
"[MSG017] Permission to shared drives mismatch. Select OK to proceed for manual authorization within $ManualAuthTimeout_min minutes or select CANCEL for Windows logoff now.",
"[MSG018] No valid reservation found. $txt",
"[MSG019] Inactive time exceeded the inactivity limit. Select OK within 60 seconds to avoid the current Windows session logoff.",
"[MSG020] Save your files now. Shutting down the system within $LastWarning_min seconds.",
"[MSG021] Your reservation is close to expire!"
return $arrMessage[$index]
}
function InformationMsgBox($msg, $msg_timeout){
$sh = New-Object -ComObject "Wscript.Shell"
return $sh.Popup($msg,$msg_timeout,$global:AppTitle,1+64)
}
As you have noted yourself, the InformationMsgBox is to blame. Every command returning output gets added to the pipeline.
return $sh.Popup($msg,$msg_timeout,$global:AppTitle,1+64) returns the 1 you see added to your array. You can suppress it's output by sending it to Out-Null.
function InformationMsgBox($msg, $msg_timeout){
$sh = New-Object -ComObject "Wscript.Shell"
return $sh.Popup($msg,$msg_timeout,$global:AppTitle,1+64) | Out-Null
}

Why is my object array doubling results?

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
}

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

Powershell: Add user to groups from array

I am trying to write a PowerShell script that will create a user based off of Department and Position and add them to the AD groups specific to that position. I have a function that creates the new user and attempts to join the user to a list of groups in an array.
function CreateUser{
$sam = "$first.$last";...;$pwd = ConvertTo-SecureString "password" -AsPlainText -Force
New-ADUser -Company "MyCompany" -Department $dept -Description $desc -DisplayName $dname -EmailAddress $email -GivenName $first -Office $office -Path $path -SamAccountName $sam -Surname $last -UserPrincipalName $email
foreach ($group in $groups) { if (Get-ADGroup $group) { Add-ADGroupMember $group $sam } }
}
I have another bit of code that creates the $groups array
$positions = #()
if ($dept -eq "CSR") { $positions += "CSR Rep","CSR Lead","CSR Manager" }
if ($dept -eq "IT") { $positions += "Sysadmin","Netadmin","Sqladmin" }
...
$groups = #()
if ($position -eq "CSR Rep") { $groups += "group1","group2","group3",...,"groupN" }
if ($position -eq "CSR Lead") { $groups += "group1","group2","group3","group4",...,"groupN" }
if ($position -eq "CSR Manager") { $groups += "group1","group2","group3","group4","group5",...,"groupN" }
if ($position -eq "Sysadmin") { $groups += "group6","group7",...,"groupN" }
if ($position -eq "Netadmin") { $groups += "group7","group8","group9",...,"groupN" }
if ($position -eq "Sqladmin") { $groups += "group10","group11","group12",...,"groupN" }
After I've specified which department and position the groups array is created and I call the CreateUsers function but I get errors back like it is an empty array.
Is there something I am missing with trying to pass the parameters to the function or is there a better way to accomplish this task?
Any assistance would be greatly appreciated.
Since your code does not show the function call and your function does not have any parameters defined i assume you are not passing anything to it.
Here is how to use parameters with three example parameters, one of them a String[]:
function CreateUser{
param(
[parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string[]] $groups,
[parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[hashtable] $userInfo,
[parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[securestring] $pwd
)
New-ADUser -Company "MyCompany" -Department $userInfo.dept -Description $userInfo.desc -DisplayName $userInfo.dname -EmailAddress $userInfo.email -GivenName $userInfo.first -Office $userInfo.office -Path $userInfo.path -SamAccountName $userInfo.sam -Surname $userInfo.last -UserPrincipalName $userInfo.email
foreach ($group in $groups) { if (Get-ADGroup $group) { Add-ADGroupMember $group $userInfo.sam } }
}
To keep the number of parameters low i have consolidated the user info into a hashtable. Hashtables are key-value sets and can be created like this:
$userInfo = #{sam="sam"; dept="department"; desc="description"; ...}
To call your function correctly do something like this:
CreateUser -groups $groups -userInfo $userInfo -pwd $pwd
You can of course add more parameters. For documentation on possible definitions and validationmethods see Technet
If you're going to create functions that are going to be more than simple things that take parameters I would strongly suggest including parameters with them. Such as:
function CreateUser{
Param([Parameter(Position=0)][string]$First = $(throw "You must specify a first name"),
[Parameter(Position=1)][string]$Last = $(throw "You must specify a last name"),
[Parameter(Position=2)][string]$Desc = $(throw "You must specify a description"),
[Parameter(Position=3)][string]$Dept = $(throw "You must specify a department"),
[Parameter(Position=4)][string]$Office = $(throw "You must specify an office"),
[Parameter(Position=5)][string]$Password = $(throw "You must specify a password"),
[string[]]$Groups
)
$sam = "$first.$last"
$pwd = ConvertTo-SecureString $Password -AsPlainText -Force
$email = "$first.$last#company.com"
$dname = "$First $Last"
$Path = "ou=$office,ou=Users,DN=company,DN=local"
New-ADUser -Company "MyCompany" -Department $dept -Description $desc -DisplayName $dname -EmailAddress $email -GivenName $first -Office $office -Path $path -SamAccountName $sam -Surname $last -UserPrincipalName $email
foreach ($group in $groups) { if (Get-ADGroup $group) { Add-ADGroupMember $group $sam } }
}
Then when you call the function you do it as such:
CreateUser "Jim" "Kirk" "Captain Extraordinaire" "Space" "$uper$ecret123" #("ExploreNewWorlds","WhereNoManHasGone")
Or you can specify arguments by name:
CreateUser -First "Jim" -Last "Kirk" -Desc "Captain Extraordinaire" -Dept "Space" -Password "$uper$ecret123" -Groups #("ExploreNewWorlds","WhereNoManHasGone")
...and while I got caught up in work trying to post this Paul beat me to it. Nice work Paul!
Edit: On a side note, I would like to introduce you to the Switch cmdlet. I think you would benefit greatly from it. While your several If statements probably do work, consider this:
Switch($position){
"CSR Rep" { $groups += "group1","group2","group3",...,"groupN";continue }
"CSR Lead" { $groups += "group1","group2","group3","group4",...,"groupN";continue }
"CSR Manager" { $groups += "group1","group2","group3","group4","group5",...,"groupN";continue }
"Sysadmin" { $groups += "group6","group7",...,"groupN";continue }
"Netadmin" { $groups += "group7","group8","group9",...,"groupN";continue }
"Sqladmin" { $groups += "group10","group11","group12",...,"groupN" }
}
That's simplistic, and in your case may not offer too much in performance improvement, but Switch offers a cleaner solution, and improved performance over several If statements. It also allows for more logic such as:
Switch($position){
{$_ -match "CSR" } { $groups += "group1", "group2" }
{$_ -match "CSR" -and -not $_ -match "Rep"} { $groups += "group3","Group4" }
}
That would add groups 1 and 2 for all CSR, and only Leads and Managers get groups 3 and 4. Anyway, just something to consider.

Resources