Upload file from my local system on Sharepoint - batch-file

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

Related

Multiple varibales from a function into an array in Powershell

I have a function that returns several things and I need to store them into an array seperately.
The code I currently have is like so:
Function ADlocation{
Try{
$ADDetails = Get-ADComputer - Identity $Servername -Properties Description,LastLogOnTimeStamp -ErrorAction SilentlyContinue -ErrorVariable ADFail
}
Catch [Exception]{
return "$($Servername) not in AD"
}
If(!ADFail){
return (Get-ADOrganizationalUnit -Identity $(ADDetails.DistinguishedName.Replace("CN=$($ADDetails.Name),","")) -Properties canonicalName).canonicalName
return $ADDetails.Description
return ([datetime]::FromFileTime($ADDetails.LastLogonTimeStamp)).ToString()
}
}
$Output = #()
foreach ($ipAddress in $iplist){
$Servername = [System.Net.Dns]::GetHostByAddress($ipAddress).Hostname
if(Test-Connection $ipAddress -Quiet){
$Output += [PSCustomObject]#{
ip = $ipAddress
Name = $ServerName
Pingable = "Yes"
ADLocation = ADlocation
AdDescription = ADlocation
LAstLogOnTime = ADlocation
}
} else {
$Output +=[PSCustomObject]#{
ip = $ipAddress
Name = "N/A"
Pingable = "No"
}
}
}
$Output | Export-Csv -path $OutputPath -NoTypeInformation
I am unsure what i should call to specifically get the "ADlocation", "ADDescription" and LastLogOnTime
There are a couple of things amiss in your code. As commented, the three return statements in the function. In fact, you don't really need a helper function for this..
Also, there is a syntax error on - Identity $Servername, where the space should not be there between the hyphen and the parameter name Identity.
Then, if you want to output a valid CSV, you need to specify the same objects with the same properties, both when succeeded and when failed.
I think the easiest way to do this, is to merge success/failed like below:
Assuming your $iplist variable is an array of IP addresses
$OutputPath = 'D:\Test\computers.csv' # enter the path and filename you want here
# loop over the IP addresses in the list
$Output = foreach ($ipAddress in $iplist) {
# initialize some variables
$pingable = 'No'
$Servername, $ADDetails = $null
if (Test-Connection -ComputerName $ipAddress -Quiet -Count 1) {
$pingable = 'Yes'
# GetHostByAddress is obsolete, use GetHostEntry
$Servername = [System.Net.Dns]::GetHostEntry($ipAddress).Hostname
# rather use Filter than Identity so exceptions can be silenced with -ErrorAction SilentlyContinue
$ADDetails = Get-ADComputer -Filter "Name -eq '$Servername'" -Properties Description,LastLogOnDate, CanonicalName -ErrorAction SilentlyContinue
}
# simply output an object to be collected in variable $Output
[PSCustomObject]#{
IP = $ipAddress
Name = if ([string]::IsNullOrWhiteSpace($ServerName)) { 'N/A' } else { $ServerName }
Pingable = $pingable
ADLocation = if ($ADDetails) { Split-Path -Path $ADDetails.CanonicalName -Parent } else { 'N/A' }
ADDescription = if ($ADDetails) { $ADDetails.Description } else { 'N/A' }
LastLogOnDate = if ($ADDetails) { $ADDetails.LastLogOnDate } else { 'N/A' }
}
}
# output on screen
$Output | Format-Table -AutoSize
# output to CSV file
$Output | Export-Csv -Path $OutputPath -NoTypeInformation

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
}

Powershell export-csv SQL User rights

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 "--------------------------------------------------------------------------------"
}
}

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
}

How to adapt Get-ChildItemToDepth to return Depth in array ?

I using PowerShell 2.0 and using a function to list all directory ending by "_S" on 2 level depth
Example where Push-Location = "\\MyServer\Shared\toto\" the result is:
\\MyServer\Shared\toto\Folder1_S
\\MyServer\Shared\toto\Folder1_S\Folder2_S
\\MyServer\Shared\toto\Folder1_S\Folder3_S
Now, i would like this function return level depth number in array
For example i would like this result
1; \\MyServer\Shared\toto\Folder1_S
2;\\MyServer\Shared\toto\Folder1_S\Folder2_S
2; \\MyServer\Shared\toto\Folder1_S\Folder3_S
.
function Get-ChildItemToDepth {
param(
[String]$Path = $PWD,
[String]$Filter = "*_S",
[Byte]$ToDepth = 2,
[Byte]$CurrentDepth = 0,
[Switch]$DebugMode
)
$CurrentDepth++
if ($DebugMode) { $DebugPreference = "Continue" }
Get-ChildItem $Path | ForEach-Object {$_ | Where-Object { ($_.Attributes -match "Directory") -and ($_.Name -like $Filter) } | Select-Object -ExpandProperty FullName
#Write-Host $CurrentDepth
if ($_.PsIsContainer) {
if ($CurrentDepth -le $ToDepth) {
# Callback to this function
Get-ChildItemToDepth -Path $_.FullName -Filter $Filter -ToDepth $ToDepth -CurrentDepth $CurrentDepth
} else {
Write-Host $("Skipping GCI for Folder: $($_.FullName) " +
"(Why: Current depth $CurrentDepth vs limit depth $ToDepth)")
}
}
}
}
How to adpat the funtion to return an array with depth ?
Instead of outputing the FullName-value, create a string with your current depth and fullname. Ex (I've also cleaned it up a bit):
function Get-ChildItemToDepth {
param(
[String]$Path = $PWD,
[String]$Filter = "*_S",
[int]$MaxDepth = 2,
[int]$CurrentDepth = 1,
[Switch]$DebugMode
)
if ($DebugMode) { $DebugPreference = "Continue" }
Get-ChildItem $Path | Where-Object { $_.PSIsContainer } | ForEach-Object {
#Write-Host $CurrentDepth
if ($_.Name -like $Filter) {
#Match found. Output "Level; Path"
"$CurrentDepth; $($_.FullName)"
}
#Recursion
if ($CurrentDepth -lt $MaxDepth) {
# Callback to this function
Get-ChildItemToDepth -Path $_.FullName -Filter $Filter -MaxDepth $MaxDepth -CurrentDepth ($CurrentDepth + 1)
} else {
Write-Host $("Skipping GCI for Folder: $($_.FullName) " +
"(Why: Current depth $CurrentDepth vs limit depth $MaxDepth)")
}
}
}
Get-ChildItemToDepth -Path \\MyServer\Shared\toto\

Resources