output site collection url in a variable from contentdb - database

I am currently trying to get one site collection URL from my content db.
After researching I found:
How to see all site collections in a specific content DB
And after changing the accepted answer a tiny bit to get only 1 site collection and only the url and assigning it to a variable I have:
$mySiteURL = Get-SPSite -Limit 1 -ContentDatabase WSS_Content_DBNAME | select url
However, when I output this variable using Write-Host $mySiteURL I get:
#{Url=http://mysites.mydomain.local}
when I only want:
http://mysites.mydomain.local
How do I do this?

You have an object array with an URL property. To dissolve the object and retain just the string you can use -ExpandProperty
$mySiteURL = Get-SPSite -Limit 1 -ContentDatabase WSS_Content_DBNAME | select-object -expandproperty url
This is one of the common gotcha's of PowerShell.

Related

Why can't I store the return value of a cmdlet [CimInstance] inside an arraylist?

I'm currently working on a script where i retrieve the following data on a host:
List of installed printers
List of installed printer drivers
List of used printer drivers
At the moment i simply achieve it this way:
$installedPrinters = Get-Printer
$installedDrivers = Get-PrinterDriver | Sort-Object -Property Name
$usedDrivers = $printerList | Sort-Object -Property DriverName | Select-Object DriverName | Get-Unique -AsString
For convenience reasons i'm now trying to use an arraylist instead of 3 different variables for storing this data but i somehow don't seem to get this to work.
As soon as i try something like that ...
$data.Add({Get-Printer})
or
Get-Printer | $data.Add($_)
... i get either a bunch of errors or simply the value 'Get-Printers' as string stored in the arraylist.
Weirdly enough it seems to work if i first store the returned data from the Get-Printer cmdlet inside a dedicated variable and then add this variable to the arraylist.
Can somebody please help me get my head around this? As of now this behaviour doesn't really seem to make any sense to me.
Your syntax is flawed.
Use one of the following (assuming that $data contains a System.Collections.ArrayList instance):
$data.AddRange((Get-Printer))
Or, less efficiently:
Get-Printer | ForEach-Object { $null = $data.Add($_) }

Powershell: Comparing a value between two arrays, and extracting a related value

so here is what I'm trying to accomplish.
I have a form for a new starter, New Starter Form.csv, that has the following headers and information:
firstname,lastname,teamname,startdate
Joe,Bloggs,Security Admin,01/01/18
I have a different csv called Team List.csv, that has the following headers and information:
teamlead,teamname,resgroup
A B,Marketing,RESMARKETING01G
C D,Product,RESPRODUCT01G
E F,Advertising,RESADVERTISING01G
G H,Security Admin,RESSECURITYADMIN01G
I want to import both CSV files into Powershell, run a comparisson that takes the team name from the New Starter Form, and checks if there are any matches in the Team List, and if so, add the relevant RES group to the new starter in AD.
Currently, I can import them, compare them, find a match, and find an index number for the record, but I'm struggling to the take this index number, and use it to get the relevant RES group. So far the code looks like this:
$teamlist = import-csv "\\location\Team List.csv"
$newstarter = import-csv "\\otherlocation\New Starter Form.csv"
[string]$teamname = Compare-Object -includeequal -excludedifferent -PassThru $newstarter.teamname $teamlist.teamname
$teamname
[array]::indexof($teamlist,$teamname)
And running that, provides us with this in the console, showing that we can indeed see the match, and that the matching record is the last (-1) one:
PS C:\WINDOWS\system32> $teamlist = import-csv "\\location\Team List.csv"
$newstarter = import-csv "\\otherlocation\New Starter Form.csv"
[string]$teamname = Compare-Object -includeequal -excludedifferent -PassThru $newstarter.teamname $teamlist.teamname
$teamname
[array]::indexof($teamlist,$teamname)
Security Administration
-1
I've not got a lot of experience with Powershell, and my coding knowledge is pretty limited overall, but I'm used to the concept that I can save the index value as a variable, and then I could call that variable back to do something like $teamlist.resgroup[VARIABLE HERE].
But if I try and declare a new variable before [array]::indexof($teamlist,$teamname), Powershell isn't happy.
Whilst I've not looked into it, I believe a possible alternative could be to add in a huge switch statement, but I may be looking at having 100+ teams overall, and I'd like to avoid inefficient code wherever I can. Am I missing something obvious though? Is there a better way (Or even just a functioning way would be great!) that this could work?
Any help you can provide would be greatly appreciated!
$teamlist = import-csv "\\location\Team List.csv"
$newstarter = import-csv "\\otherlocation\New Starter Form.csv"
# get a single new starter
$person = $newstarter | Where-Object { $_.firstname -eq 'Joe' -and $_.lastname -eq 'Bloggs' }
# get the new starters team
$team = $teamlist | Where-Object { $_.teamname -eq $person.teamname }
# get the new starters resource group
$resgroup = $team.resgroup
# use the resource group - this simply writes it to the console
Write-Host $resgroup
The code above will:
import your two csvs
grab a single new starter from your new starter csv, based on first &
last name
grab the team & resource group for that new starter from the team list
display the resgroup (this is where you will need to use to populate AD)

filling attribute with concatenated string

I am looking for a way to concatenate a string and put it in one active directory user account object, to be precise, in altsecurityidentities.
The value to be input will be as following:
" which is constant, and (firstName)(whitespace)(lastname) (custom value which can be taken from another attribute, which is in form x.yyyyyyyy.z (what matters to me is yyyyyyy part (.substring(2,8)) works like charm here.
I'd like to do it for several accounts that are listed in variable of type TypeName: Microsoft.ActiveDirectory.Management.ADUser.
So that it can be set for all accounts under $accounts variable.
So far I have the code to create the attribute value for one account listed in there:
$accounts | %{'constant value'+$.givenname+' '+$.surname+' '+'('+$(($_.attributename).substring(2,8))+')'}
This, i'd like to put in altsecurityidentities attribute value, log to event viewer success and errors
You're almost there really just need to apply the value to the desired field:
$accounts | ForEach-Object { Set-ADUser -Identity $_ -Add #{altsecurityidentities = "constant value $($_.givenname) $($_.surname) ($($_.attributename.substring(2,8)))"} }
I have tidied up your code by embedding the variables in a string rather than using concatenation, which is much cleaner.

Index is out of range powershell

I have a script that builds a GUI with a list of printers that will be selected by the user.
These printers are also on a CSV file built like this :
Computer (name of the printer); IP
xxxx;x.x.x.x
I want to collect all the selected values in an array named x
Then I want to take every entry in the CSV that corresponds to the selected item and put it in another array named y
Finally I export the y array into a new CSV that will be used to install the printers on the domain.
I tried to go straight from second step to last step but i couldn't.
Here is the part of the code :
$OKButton.Add_Click({
foreach ($objItem in $objListbox.SelectedItems)
{$x += $objItem}
y=#()
for ($i=0; $i -lt $x.length; $i++)
{
$y[$i]=Import-Csv C:\Users\Administrateur\Desktop\Classeur33.csv | Where-Object {$_.Computer -eq $x[$i]}
}
$y > C:\Users\Administrateur\Desktop\allezjoue.csv
I've tried to do it with a 3 values x array in another script and it worked fine, but I really need to keep the listbox that allows the user to select the printers he wants.
Powershell always returns me "Index out of range"
I tried to put "$y=$x" so they have the same range, but when I do this it returns that I can't index in an object which has "System.string" type.
This is PowerShell and very object oriented. Use the objects and collections at hand.
Decriptive variable names are your friend.
$objListbox.SelectedItems is already a collection of objects.
Put it in a variable and loop through it with Foreach-Object aka foreach.
Import-CSV returns a collection of objects.
$Selection = $ObjListbox.SelectedItems
$printers = Import-CSV 'C:\Users\Administrateur\Desktop\Classeur33.csv'
foreach ($chosen in $Selection) {
$printers = $printers | where-object { $_.Computer -eq $Chosen.Name }
}
$printers | Export-CSV 'C:\Users\Administrateur\Desktop\allezjoue.csv' -NoTypeInformation
$Chosen.Name should be edited to conform with whatever objects you get in $Selection. You can test this by $ObjListbox.SelectedItems | Get-Member and examining the members for a property with the name of the item selected, then assuming the names match what's in your CSV, you should be good.
(bonus note) Storing data in and running as local admin is bad practice, even on your home lab. Your mistakes will have the power of local admin, and your users will not be able to run the scripts since the source/results files are in admin's desktop.

Selecting certain properties from an object in PowerShell

The ADSI query works fine, it returns multiple users.
I want to select the 'name' and 'email' from each object that is returned.
$objSearcher = [adsisearcher] "()"
$objSearcher.searchRoot = [adsi]"LDAP://dc=admin,dc=domain,dc=co,dc=uk"
$objSearcher.Filter = "(sn=Smith)"
$ADSearchResults = $objSearcher.FindAll()
$SelectedValues = $ADSearchResults | ForEach-Object { $_.properties | Select -property mail, name }
$ADSearchResults.properties.mail gives me the email address
When I omit the 'select -properties' it will return all the properties, but trying to select certain properties comes back with nothing but empty values.
Whenever working with ADSI I find it easier to expand the objects returned using .GetDirectoryEntry()
$ADSearchResults.GetDirectoryEntry() | ForEach-Object{
$_.Name
$_.Mail
}
Note: that doing it this way gives you access to the actual object. So it is possible to change these values and complete the changes with something like $_.SetInfo(). That was meant to be a warning but would not cause issues simply reading values.
Heed the comment from Bacon Bits as well from his removed answer. You should use Get-Aduser if it is available and you are using Active Directory.
Update from comments
Part of the issue is that all of these properties are not string but System.DirectoryServices.PropertyValueCollections. We need to get that data out into a custom object maybe? Lets have a try with this.
$SelectedValues = $ADSearchResults.GetDirectoryEntry() | ForEach-Object{
New-Object -TypeName PSCustomObject -Property #{
Name = $_.Name.ToString()
Mail = $_.Mail.ToString()
}
}
This simple approach uses each objects toString() method to break the data out of the object. Note that while this works for these properties be careful using if for other and it might not display the correct results. Experiment and Debug!
Have you tried adding the properties?
$objSearcher.PropertiesToLoad.Add("mail")
$objSearcher.PropertiesToLoad.Add("name")

Resources