Powershell Pipeline Variable No Output - powershell

I'm trying to get all the user photos from my office365 server. I need them to show in the Alias format which is firstname.lastname
get-mailbox | % {Get-UserPhoto $_.alias} | % {Set-Content -path "c:\export\$($_.alias).jpg" -value $_.picturedata -Encoding byte}
This works, but gives me First Name Last Name
Someone told me I need to pass mailbox parameters through the pipeline, to do what I want to do.
get-mailbox -PipelineVariable Mailbox | % {Get-UserPhoto $Mailbox.alias} | % {Set-Content -path "c:\export\$($Mailbox.alias).jpg" -value $_.picturedata -Encoding byte}
This is my new code, but it's not spitting out photos into directory. Does anyone know why this isn't working?

Cannot check this now, but I think this may work:
Get-Mailbox | ForEach-Object {
$photo = Get-UserPhoto -Identity $_.alias
Set-Content -Path "c:\export\$($_.alias).jpg" -value $photo.picturedata -Encoding byte
}

Related

Output Powershell results to individual text documents

I figured this might be an easy answer, but for the life of me I can't suss out why this simple thing seems to be beating me. I am looking to output the results of
Get-Mailbox –Server MYserverName | Get-MailboxPermission | FL
piped into individual text files for each individual mailbox, with the text file named for the mailbox - e.g. I want to have a folder with the content:
C:\Example\MailboxUser1.txt
C:\Example\MailboxUser2.txt
C:\Example\MailboxUser3.txt
with each containing the mailbox permission results.
I know I can do a foreach loop along the lines of:
ForEach-Object {Out-file $_.name}
to generate the output files, but I'm not too sure how I would do this in a single step to get the permissions for all my mailboxes into individual files (I know this will give me a lot of text files!)?
Something along the lines of:
$directory = "C:\example\"
$count = 0
Get-Mailbox –Server "MYserverName" | Foreach-Object {
Get-MailboxPermission | Format-List |
Out-File (Join-Path $directory "MailboxUser-$(++$count).txt")
}
At each pass of the ForEach-Object loop (mailbox), a file will be generated with the output of the Get-MailboxPermission command.
++$count increments the value just before using it (as opposed to $count++)
If you prefer to user the Name property of the mailbox object to name the files:
$directory = "C:\example\"
Get-Mailbox –Server "MYserverName" | Foreach-Object {
$mailboxName = $_.Name
Get-MailboxPermission | Format-List |
Out-File (Join-Path $directory "MailboxUser-$mailboxName.txt")
}
Get-Mailbox –Server MYserverName | Get-MailboxPermission | foreach {out-file "$($_.name).txt"}
This would be able to get you all the permissions you need IF "name" was the property you were looking at. I don't work with exchange cmdlets so I don't know if that will count.

PowerShell foreach loop export to new column in CSV format

I am currently working with a CSV file that has a manager's employee number, but not their SAMAccountName. I want to utilize Get-ADUser to grab the manager's SAMAccountName from their EmployeeNumber attribute and place that inside a new column in the same CSV file.
CSV sample:
"Full Name","Username","Manager","Manager User Sys ID"
"User 1","u1","1, Manager","123456"
"User 2","u2","2, Manager","234567"
"User 3","u3","3, Manager","345678"
I would like:
"Full Name","Username","Manager","Manager User Sys ID","Manager SamAccountName"
"User 1","u1","1, Manager","123456","m1"
"User 2","u2","2, Manager","234567","m2"
"User 3","u3","3, Manager","345678","m3"
I have spent some time putting together the following code. I can get a new column added and can further grab the SAMAccountName, but it only exports a single line in the new CSV file like this:
"SAMAccountName","managerUsername"
"m1","#{SAMAccountName=m1}"
Here is the code:
$managers = Import-Csv -Path .\test.csv
$usermananger = #()
foreach ($manager in $managers)
{
$getmanagersam = Get-ADUser -Filter "employeeNumber -eq $($manager."Manager User Sys ID")" -Properties SAMAccountName |
Select-Object SAMAccountName
$exportstring = $testmanager |
Select-Object *,#{Name='managerUsername';Expression={"$getmanagersam"}}
$exportstring | Export-Csv -Path .\simpletest.csv -NoTypeInformation
}
As #MathiasR.Jessen mentioned in the comments: you need to expand the SamAccountName property to get just the value. Also, you're overwriting your output CSV with every iteration. Either append to the file, or move the Export-Csv cmdlet outside the loop. The former requires PowerShell v3 or newer, the latter requires that you change the loop to a ForEach-Object loop (or run the foreach loop in a subexpression).
Personally I'd prefer using a pipeline, so I'd pick the latter:
Import-Csv -Path .\test.csv | ForEach-Object {
$acct = Get-ADUser -Filter "employeeNumber -eq $($_.'Manager User Sys ID')" |
select -Expand SamAccountName
$_ | select *,#{Name='managerUsername';Expression={$acct}}
} | Export-Csv -Path .\simpletest.csv -NoTypeInformation
The short answer is to add the -Append option to your export-csv statement to stop it overwriting each time round the loop.
Alternatively move the export outside the loop as follows:
$managers = Import-Csv -Path .\test.csv
$managers|foreach-object{
$getmanagersam = Get-ADUser -Filter "employeeNumber -eq $($_.'Manager User Sys ID')" | select -ExpandProperty SAMAccountName
$_|Select *,#{Name='managerUsername';Expression=$getmanagersam}
} | Export-Csv -Path .\simpletest.csv -NoTypeInformation
Note: looks like #AnsgarWiechers beat me to it :-)
I'm late to the party it looks like, but that rarely stops me... I'm not a huge fan of adding properties via the Select cmdlet, so I'm going to offer an alternative where you pipe the CSV to a ForEach-Object loop (just like the other answers), but inside that you use Add-Member with the -PassThru argument, and then pipe it off to the output file. I will add a new line and indent after the pipes, just to make it easier to read.
Import-Csv -Path ".\test.csv" |
ForEach-Object {Add-Member -InputObject $_ -NotePropertyName 'managerUserName' -NotePropertyValue (Get-ADUser -Filter "employeeNumber -eq $($_.'Manager User Sys ID')").samaccountname -PassThru} |
Export-Csv -Path ".\simpletest.csv" -NoTypeInformation
This should essentially do the exact same thing as the other two answers, it just adds the property differently, because variety is the spice of life! (I saw that on the internet somewhere, so it must be true.)

Get a list of mailboxes where AD group has permissions

I am trying to get a list of mailboxes that have a an AD group listed in their permissions.
All the AD groups I am interested in start with the same 3 characters.
I have....
get-mailbox -resultsize unlimited | Get-MailboxPermission | where {$_.user.tostring() -like "xxx*"} | out-file $file -append -noclobber -encoding ascii
but it doesn't seem to put anything in the file
What am I doing wrong?
TIA
Andy
I have a sneaking feeling there will be more questions after this but part of the issue is you loose the mailbox details when they are being passed into the cmdlet Get-MailboxPermission. If you match criteria was a little more refined your output would just be the groups that matched but not to which mailbox.
$file = "c:\temp\test.csv"
$matchPrefix = [regex]::Escape("Ex") # We use escape incase of special charaters in regex. Period would be one to expect.
$regex = "YOURDOMAIN\\$matchPrefix" # Keep those backslashes
Get-Mailbox mc* | ForEach-Object{
$results = $_ | Get-MailboxPermission | Where-Object{$_.User.ToString() -match $regex}
If($results){$_}
} | Select Name,Alias | Export-CSV $file -Append -NoTypeInformation
This will take every mailbox and check each for the presence of the group/user. Using $regex we check each of the located user/groups. If they are present then the -match would return True satisfying the Where block and the mailbox is passed in the pipeline to be exported.
For the export we just send the mailbox name and alias to a csv file specified by $file
Caveats
-Append is available in PowerShell 3.0 which you exchange might not have. I could just be removed.
Assumptions
I am assuming you want just the mailboxes that match the group prefix you specify. If you want the actual groups that match it is possible with a little extra logic. I would like to know if what I suggest is sufficient before I guess more.
This code works, and it is also clear as to which mailbox these permissions belong:
get-mailbox -resultsize 1000 | foreach{
Write-Host $_.PrimarySMTPAddress -ForegroundColor Green;
$permissions = Get-MailboxPermission $_.PrimarySMTPAddress | ?{$_.User -match "Ryan"}
if($permissions){
$permissions | FT -AutoSize;
$_.PrimarySmtpAddress | Out-File C:\Test.txt -append -noclobber -encoding ascii;
$permissions | FT -AutoSize | Out-File C:\Test.txt -append -noclobber -encoding ascii;
}
}
Please note: I checked to see what $_.user.tostring() produces in order to know what I am looking for with respect to the "match" Boolean logic.

Powershell Out-File output all on the same line

I have a powershell script that populates a variable, $Users, from the contents of a text file using the Get-Content cmdlet. I then want to append this information to the end of a different text file using Out-File. However, currently the output is appended all in a row. What I need is for each string to be on it's own line.
I have tried piping the variable into the Write-Output cmdlet and it displays correctly on the screen, but when I redirect it from Write-Output back to the Out-File cmdlet it appends the information all in a row again.
$Users = Get-Content "C:\Users\XXXX\Desktop\Password Reset\Users5.txt"<br>
Out-File -InputObject $Users -FilePath "C:\Users\XXXX\Desktop\Password Reset\RefUsers.txt"
If it was me I would use Add-Content for this with a pipe.
$Users = Get-Content -Path "C:\Users\XXXX\Desktop\Password Reset\Users5.txt"
$Users | Add-Content -Path "C:\Users\XXXX\Desktop\Password Reset\RefUsers.txt"
Pay attention to encoding. Add-Content uses ascii by default I believe. Also if you are not doing anything with the data you can skip the variable all together.
GC "C:\Users\XXXX\Desktop\Password Reset\Users5.txt" |
AC "C:\Users\XXXX\Desktop\Password Reset\RefUsers.txt"
Gc being an alias for Get-Content and Ac for Add-Content
Here is how my final script turned out:
$Users = Get-Content "C:\Users\XXXX\Desktop\Password Reset\Users5.txt"
Foreach($U in $Users){
Add-Content "C:\Users\XXXX\Desktop\Password Reset\RefUsers1.txt" "`n$U"
}
Thanks Matt!

Powershell Append CSV

I am trying to append a CSV file. Here are the lines I am using. I wasn't able to find an append option for export-csv unfortunately. Any ideas would be helpful to get this to work.
Get-ADGroupMember "Domain Admins" | select name, samaccountname | Export-Csv c:\bin\DomainAdmins.csv
$admins = Import-Csv C:\bin\DomainAdmins.csv
foreach ($i in $admins) {Get-ADUser $i.samaccountname -properties * | select name, lastlogondate | Export-Csv c:\bin\dalogon.csv}
The documentation suggests that there is an -append flag. The example given ends with
| export-csv –append –path \\Archive01\Scripts\Scripts.csv
Have you tried that? It works fine for me. I'm on version 3, if that matters.
-Append was introduced with PowerShell v3, it's not available in PowerShell v2 and earlier. You can work around it like this, though:
... |
ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1 |
Out-File -Append "c:\bin\dalogon.csv"
I ran into this issue also a few days ago. There are a really two solutions I know in Powershell 2. The first would be to save all the data in an array and then use the export-csv commandlet. That did not work for me unless I rewrote my script. I needed to create a CSV and append line by line to build the file. So, I solved it with out-file -append and changing the encoding to ascii.
I basically created a string with my data in it and then piped it to out-file. Here is an example:
$myCSV = "C:\_PSScripts\data\myCSV.csv"
$firstOutputLine = "Column-1,Column-3,Column-3"
$firstOutputLine | out-file $myCSV -Encoding ascii -Force -Append
It's good! but it's only 1 column in CSV file! how to put to many columns as the code below:
Import-Module -Name 'C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ArsPowerShellSnapIn.dll'
$group="HO-Internet","Internet1","Internet2","Internet3"
$group |ForEach-Object {Echo "--------------------Group Name $_ ----------------"; Get-QADGroupMember $_ | Select-Object Email,LogonName,ParentContainer,LastLogon,AccountIsDisabled |ConvertTo-Csv -NoTypeInformation `
| select -Skip 1 `
| Out-File -Append "D:\test.csv"}