Again with Powershell: I know how to create a file but I don't know how to write in it [duplicate] - powershell

I am creating a script and want to both use Write-Host and Write-Output
As I work I want a backup of information I pull from AD to also become attached to a .txt file.
This is more of a backup in case I miss a piece of information and need to go back and recreate a ticket. Anyways I have a sample of my script, form what I can tell it should be working. If someone with a bit more experience can take a look or point me in the right direction I would appreciate it. If I need to add any more of the script I can provide this. Thanks in Advance.
Import-Module activedirectory
$object = Get-ADUser $sid -Properties * | Select-Object EmailAddress
Write-Host Email: $object.EmailAddress
Write-Output ("Email: $object.EmailAddress") >> C:\psoutput\psoutput.txt -Append
This will create the .txt file of course but is also add other information such as:
Email: #{GivenName=myfirstname; Surname=mylastname; SamAccountName=myid; DisplayName=lastname, firstname - Contingent Worker; City=; EmailAddress=myemailaddress#mywork.com; EmployeeID=; Enabled=True; OfficePhone=; MobilePhone=(555) 555-5555; LockedOut=False; LockOutTime=0; AccountExpirationDate=05/09/2020 00:00:00; PasswordExpired=False; PasswordLastSet=12/03/2019 12:16:37}.EmailAddress
-Append
I am looking to have the output like the following...
name: username
email: user email address
phone: user phone number
etc...
All general information from Active Directory
Thanks again for the suggestions

Don't use write-output. Use (Get-ADUser $sid -properties mail).mail.
Like this:
Add-Content -Path "FilePath" -Value "Email: $((Get-ADUser $sid -properties mail).mail)"

Write-Output ("Email: $object.EmailAddress")
As an aside: No need for (...) here.
This doesn't do what you expect it to: it stringifies $object as a whole and then appends .EmailAddress verbatim; in order to embed an expression, such as accessing a property inside "..." (an expandable string), you need $(), the subexpression operator.
Write-Output "Email: $($object.EmailAddress)" >> C:\psoutput\psoutput.txt
See this answer for an overview of the syntax in PowerShell expandable strings.
Or, more simply, using PowerShell's implicit output behavior (use of Write-Output is rarely necessary):
"Email: $($object.EmailAddress)" >> C:\psoutput\psoutput.txt
>> C:\psoutput\psoutput.txt -Append
>> is effectively an alias for Out-File -Append (just like > is for just Out-File), so not only is there no need for -Append, it isn't interpreted by >>, which accepts only the filename operand.
Instead, -Append was interpreted by Write-Output, which is why it ended up literally in your output file.
Perhaps surprisingly, while a redirection such as >> C:\psoutput\psoutput.txt is typically placed last on the command line, that is not a syntactic requirement: other arguments may follow.
I am looking to have the output like the following..
It sounds like you want formatting as provided by the Format-List cmdlet:
$object | Format-List >> C:\psoutput\psoutput.txt
Note that > / >> / Out-File apply the default string formatting, i.e. the same representation that would by default display in the console.
By using an explicit Format-* cmdlet, you can control that formatting, but note two things about Out-File in general:
As you're outputting for-display formats, the resulting file may not be suitable for further programmatic processing.
To prevent truncation of values, you may have to pass a -Width argument to Out-File, control the enumeration length of nested properties with $FormatEnumerationLimit, and, in the case of Format-Table, specify -AutoSize.

You don't really need to use Write-Output at all. Try this to just get your string to your file:
("Email: " + $object.EmailAddress) >> C:\psoutput\psoutput.txt
You don't need to specify append because '>>' already does that for you

Related

Mapping Multiple IDs to their Email Address in Active Directory and Outputting Results to a Single File

I am trying to find a method to map IDs of multiple users to their associated email addresses in Active Directory (AD), and subsequently append the outputs into a txt file, ultimately generating a single file with a list of email addresses. Via the following command leveraging PowerShell AD Tools, I can output the email address of a certain user:
$user= testID
Get-ADUser $user -server ml -Properties * | Select-Object mail
Now I'm trying to adapt this to work across multiple users, although the method I've come across does not append or concatenate each result to the txt file. Each new output when the loop iterates overwrites the contents of the existing text file.
$multiple_users = "testID1", "testID2", "testID3"
foreach ($multiple_user in $multiple_users){
Get-ADUser $multiple_user -server ml -Properties * | Select-Object mail > ID_to_email.txt
}
Any direction or insight, is much appreciated!
Thank you
Building on Abraham Zinala helpful comment:
The immediate fix is to replace > with >> inside your foreach loop:
Redirection > is in effect an alias for Out-File therefore replaces the target file in every iteration, which is not what you want.
By contrast, >> is in effect an alias for Out-File -Append and therefore appends to the target file.
However, using >> inside a loop is best avoided, because it is:
inefficient, because the target file must be opened and closed in every iteration.
inconvenient, in that you must ensure that the target file doesn't exist yet or is empty before the loop, so as not to accidentally append to preexisting content.
Therefore, it is preferable to use a pipeline with a single Out-File call / > operation that receives the output from all iterations in a streaming fashion:
Note:
A foreach statement cannot directly be used in a pipeline and therefore with a redirection, which is why the similar ForEach-Object cmdlet is used below, to which the $multiple_users array is piped, causing its elements to be processed one by one, as reflected in the automatic $_ variable.
Alternatively, you can wrap a statement such as foreach or while in & { ... } or . { ... } to allow it to participate in a pipeline; e.g.:& { foreach ($i in 1..2) { $i } } > out.txt
The solution below applies analogously to use of the Set-Content cmdlet (which is more efficient than > / Out-File if you know the objects to write to the file to be strings already): use a single Set-Content call at the end of the pipeline (instead of calling Add-Content in every loop iteration).
$multiple_users |
ForEach-Object {
Get-ADUser $_ -server ml -Properties mail |
Select-Object mail
} > ID_to_email.txt # Write ALL output to ID_to_email.txt
Instead of > ID_to_email.txt, you could use | Out-File ID_to_email.txt instead; explicit use of Out-File is required in the following cases:
to force interpretation of the target file path as a literal path, with -LiteralPath, notably if it contains [ and ] (perhaps surprisingly, > and Out-File with the (often positionally implied) -FilePath parameter treat paths as wildcard expressions - see this answer).
to control the character-encoding to use for the output file, via the -Encoding parameter.

PowerShell: get object properties in a readable table

I am trying to display StrongAuthenticationMethods from the azure object (user) in a more readable way inside of the script which will reset the MFA method.
When I call variable $mfa
$UserPname = Read-Host "Please enter e-mail address"
$AzureUser=Get-MsolUser -UserPrincipalName "$UserPname"
$methode = $AzureUser.StrongAuthenticationMethods
$mfa = $methode | Select-Object MethodType, IsDefault
$mfa
it gives me a nice table:
---------- ---------
PhoneAppOTP False
PhoneAppNotification True
When I try to write-host this variable:
Write-Host $mfa
It gives me:
Write-Host $mfa
#{MethodType=PhoneAppOTP; IsDefault=False} #{MethodType=PhoneAppNotification; IsDefault=
True}
How can I display this MethodType and IsDefault properties in the best readable way using
write-host?
Thanks for the information in advance!
Write-Host ($mfa | Format-Table | Out-String)
To print synchronous, richly formatted output to the host (display), use the Out-Host cmdlet rather than Write-Host: Out-Host uses PowerShell's rich formatting system, whereas Write-Host essentially performs .ToString() stringification, which often results in unhelpful output.
# Forces instant output to the display,
# but note that such output *cannot be captured*.
# Use ... | Format-Table | Out-Host to force tabular formatting,
# but with a custom object with 4 or fewer properties that isn't necessary.
$mfa | Out-Host
Judging by your later comments, the reason you want this is the well-known problem of the situational lack of synchronization between pipeline output and to-host output (as well as output to other streams), which can cause displayed output to print out of order.
# !! Read-Host executes FIRST
[pscustomobject] #{ print='me' }
Read-Host 'Press ENTER to continue'
# Workaround: Out-Host forces instant printing to the display,
# but note that such output then cannot be captured.
[pscustomobject] #{ print='me' } | Out-Host
Read-Host 'Press ENTER to continue'
The problem is limited to a very specific - albeit common - scenario: implicitly table-formatted output for types that do not have formatting data defined for them.
See this answer for a detailed explanation.
See GitHub issue #4594 for a discussion of this problematic behavior.

Trying to test code, keep getting "System.____comobject" instead of variable value

I'm trying to write a small powershell script that does a few things
1) Parses Inbox items in my outlook
2) Searches for a RegEx string
3) Dumps the line that matches the RegEx string into a CSV
I can't get #3 to work. It definitely runs for about 10 minutes, but the resulting csv is empty.
Here's a snippet of what I want it to look for:
Account Name: Jbond
I tried just slapping a "Write-Host $variable" in various parts to see what was happening, but all I get is "System.____comobject". I can't find a solution online to just convert this into plain text.
Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$namespace = $Outlook.GetNameSpace("MAPI")
$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)
$RE = [RegEx]'(?sm)Account Name\s*:\s*(?<AccName>.*?)$.*'
$Data = ForEach ($item in $inbox.items){
$resultText = $item.item.Value
Write-Host $resultText
if ($item.from -like "email#email.org"){
if ($item.body -match $RE){
[PSCustomObject]#{
AccName = $Matches.AccName
}
}
}
}
$Data
$Data | Export-CSv '.\data.csv' -NoTypeInformation
tl;dr:
Use:
$variable | Out-Host # or: Out-Host InputObject $variable
rather than
Write-Host $variable
to get meaningful output formatting.
Background information and debugging tips below.
Try a combination of the following approaches:
Use interactive debugging:
Use GUI editor Visual Studio Code with the PowerShell extension to place breakpoints in your code and inspect variable values interactively. (In Windows PowerShell you can also use the ISE, but it is obsolescent.)
Less conveniently, use the *-PSBreakpoint cmdlets to manage breakpoints that are hit when you run your script in a console (terminal) window. A simple alternative is to add Wait-Debugger statements to your script, which, when hit, break unconditionally.
Produce helpful debugging output:
Generally, use Write-Debug rather than Write-Host, which has two advantages:
You can leave Write-Debug calls in your code for on-demand debugging at any time:
They are silent by default, and only produce output on an opt-in basis, via (temporarily) setting $DebugPreference = 'Continue' beforehand or passing the -Debug switch (if your script / function is an advanced one, though note that in Windows PowerShell this will present a prompt whenever a Write-Debug call is hit).
You do, however, pay a performance penalty for leaving Write-Debug calls in your code.
Debug output is clearly marked as such, colored and prefixed with DEBUG:.
The problem you experienced with Write-Host is that all Write-* cmdlets perform simple .ToString() stringification of their arguments, which often results in unhelpful representations, such as System.____comobject in your case.
To get the same rich output formatting you would get in the console, use the following technique, which uses Out-String as a helper command:
$variable | Out-String | Write-Debug
If you want to control the view (list vs. table vs. wide vs. custom) explicitly, insert a Format-* call; e.g.:
$variable | Format-List | Out-String | Write-Debug
It is generally only the standard Out-* cmdlets that use PowerShell's output formatting system.
A quick-and-dirty alternative to Write-Debug is to use Out-Host rather than Write-Host - e.g., for quick insertion of debugging commands that you'll remove later; Out-Host itself performs the usual output formatting, which simplifies matters:
# Default for-display formatting
$variable | Out-Host # or: Out-Host -InputObject $variable
# Explicit formatting
$variable | Format-List | Out-Host
Caveat: Aside from formatting, another important difference between Write-Host and Out-Host is that in PSv5+ only Write-Host writes to the host via the information stream (stream number 6), whereas Out-Host truly writes directly to the host, which means that its output cannot be captured with redirections such as 6> or *> - see about_Redirection.

PowerShell Log Function Readability

Currently my log function spits out the information in a single column and is hard to read. Is there a way to make it split up into different columns which each (DisplayName, PoolName, PoolSnapshot, and DesktopSVIVmSnapshot) and its respective information is put correctly?
function log ([string]$entry) {
Write-Output $entry | Out-File -Append "C:\logs\SNAPSHOT.csv"
}
Add-PSSnapin Quest.ActiveRoles.ADManagement
$date = Get-Date -Format "MM-dd-yyyy"
$time = Get-Date -Format "hh:mm:sstt"
# begin log
log $(Get-Date)
log "The below Desktops are not using the correct Snapshot."
if (#($DesktopExceptions).Count -lt 1) {
Write-Output "All desktops in $pool are currently using the correct snapshots." |
Out-File -Append "C:\logs\SNAPSHOT.csv"
} else {
Write-Output $DesktopExceptions |
Select-Object DisplayName,PoolName,PoolSnapshot,DesktopSVIVmSnapshot |
sort DisplayName |
Out-File -Append "C:\logs\SNAPSHOT.csv"
}
log $(Get-Date)
09/11/2017 12:16:17
DisplayName PoolName PoolSnapshot DesktopSVIVmSnapshot
----------- -------- ------------ --------------------
xxxc-13v xxxc-xxx /8-11-2017/09-07-2017 /8-11-2017
xxxc-15v xxxc-xxx /8-11-2017/09-07-2017 /8-11-2017
xxxc-1v xxxc-xxx /8-11-2017/09-07-2017 /8-11-2017
xxxc-20v xxxc-xxx /8-11-2017/09-07-2017 /8-11-2017
Note: I removed parts of the log for in the hopes to not make the post long.
CSV files require uniform lines: a header line with column names, followed by data lines containing column values.
By writing the output from Get-Date first - a single date/time string - followed by another single-string output, followed by multi-column output from your $DesktopExceptions | Select-Object ... call, you're by definition not creating a valid CSV file.
If you still want to create such a file:
log (Get-Date) # With a single command, you don't need $(...) - (...) will do.
log "The below Desktops are not using the correct Snapshot."
If ($DesktopExceptions) # a non-empty array / non-$null object
{
log ($DesktopExceptions |
Select-Object DisplayName,PoolName,PoolSnapshot,DesktopSVIVmSnapshot |
Sort-Object DisplayName |
ConvertTo-Csv -NoTypeInformation)
}
Else
{
log "All desktops in $pool are currently using the correct snapshots."
}
log (Get-Date)
By defining your log() function's parameter as type [string], you're effectively forcing stringification of whatever object you pass to it. This stringification is the same you get when you embed a variable reference or command inside "..." (string expansion / interpolation) - but it is not the same as what you get by default, when you print to the console.
Out-File, by contrast, does result in the same output you get when printing to the console, which, however, is a format for human consumption, not for machine parsing (as CSV is, for instance).
To get CSV-formatted output, you must either use Export-Csv - to write directly to a file - or ConvertTo-Csv- to get a string representation.
Also note that there's typically no reason to use Write-Output explicitly - any command / expression's output that is not explicitly assigned to a variable / redirected (to a file or $null) is implicitly sent to PowerShell's [success] output stream; e.g., Write-Output Get-Date is the same as just Get-Date.
It looks like you're just writing an object, and taking the default PowerShell formatter behavior.
A better thing to do is make your log only responsible for one thing - writing messages to a file (no formatting). Here's an example of what you might try:
function Write-LogMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, HelpMessage = "The text-content to write to the log file.",
ValueFromPipeline = $true)]
[string]$Text
)
Process {
Write-Host -ForegroundColor Green $Text
}
}
Set-Alias log Write-LogMessage
Note: This example writes directly to the PowerShell console, but you would in practice need to direct output to a file (using Out-File or one of the redirection operators - see Get-Help about_Operators).
To use it, you would write something like this:
"This is a message that would be written" | Write-LogMessage
For your specific example, you could just format the message inline, and pipe it:
Write-Output $DesktopExceptions | Select-Object DisplayName,PoolName,PoolSnapshot,DesktopSVIVmSnapshot | sort DisplayName | ForEach-Object { "{0}: Host = {1}, Pool = {2}, Pool SN = {3}, SVIV Snapshot = {4}" -f (Get-Date), $_.DisplayName, $_.PoolName, $_.PoolSnapshot, $_.DesktopSVIVmSnapshot } | log
Note that you don't need the log statement: just add formatting before piping to the Out-File cmdlet, and you'll get what you're after.
Edit: The OP asked in the original post how to format columns (tabular output). To achieve this, you can use either the ConvertTo-Csv or Export-Csv cmdlets (generally, you would use the -NoTypeInformation switch parameter with these commands, to avoid the first line of the output being a type definition). An example of this is:
$DesktopExceptions | Select-Object DisplayName,PoolName,PoolSnapshot,DesktopSVIVmSnapshot | sort DisplayName | Export-Csv C:\Temp\Datum.csv -NoTypeInformation
As pointed out in another answer, using Write-Output is not required, because PowerShell automatically writes all output to the output stream unless otherwise directed (using file redirection, a redirection operator, or the Out-Null cmdlet).
Please read my answer as part solution and part advice.
The "problem" with PowerShell is that it doesn't capture only the output of your code. It will capture output from other scripts, modules and executables. In other words, any attempt to make logging behave like it's generated by e.g. C# with NLOG, has an inherent problem.
I looked into this subject myself for a complex continuous delivery pipeline I'm building. I understood that a structured log will not be 100% possible and therefore I accepted the purpose of PowerShell transcription (Start-Transcript). But still I wanted to avoid creating functions like Write-Log and if possible provide an enhanced output for all code that uses Write-Debug, Write-Verbose functionality.
I ended up creating XWrite PowerShell module which works very well, even to my own suprize. I use it because it enhances the produced trace message by the caller's name (cmdlet or script) and a timestamp. The caller's name helps a lot with troubleshooting and the timestamp I use to implicitly benchmark. here are a couple of example
DEBUG: Test-MyXWrite.ps1: Hello
DEBUG: Script: Test-MyXWrite.ps1: 20170804: 10:57:27.845: Hello
There are some limitations though. Any binary's code trace output will not be enhanced. Also if a cmllet refers explicitly to the Write-* using their full namespace it will not work. To capture line by line all trace and output requires some very deep into the .net types of PowerShell implementation hooking. There is a guy who has done this, but I don't want to get influence the PowerShell process's behavior that aggresively. And at this moment I believe that to be the role of the transcription.
If you like the idea, install the module from XWrite
At some point, I would like to extend the module with a redirection to telemetry services, but I've still not decided I want to do that, because I will not capture the above mentioned exceptions and other executable. It will just offer me visible progress as the script is executing.

Powershell - avoid repeating arguments of Out-File

Is there any way to avoid passing parameters to a function, like "-Append $outfile" to Out-File, every time? I have a script which collects data from the system, something like:
... collect OS information ... | Out-File -Append $output
... collect local users ... | Out-File -Append $output
... collect logfile permissions ... | Out-File -Append $output
etc.
The last command in the pipe is most of the time Out-File -Append $output - can this be done more elegant? I had different ideas:
Create a wrapper function which passes the needed parameters to Out-File command - already tried, but I had problems to make it pipe-compatible
Write all output into a String-Variable and write the content at the end of all commands into the file - needs a lot of memory
Create something like an Output-Writer-Object which only receives once at initialization the necessary paramters - not tried yet
Thank you very much for your help!
You dont appear to be using a lot of arguments for this to be incredibly useful but a good suggestion would be to use splatting. I added some more parameters to illustrate how clean it can make code appear while still being functional.
$options = #{
Append = $True
FilePath = $output
Encoding = "Unicode"
Width = 400
}
Build a hastable of options and splat the cmdlet with them
... collect OS information ... | Out-File #options
... collect local users ... | Out-File #options
... collect logfile permissions ... | Out-File #options
Outside of that a wrapper function (of filter if it is easier) like you suggest would be another option. Look at the options in this answer. Specifically the filter
You want to use the $PSDefaultParameterValues preference variable. Something like this:
$PSDefaultParameterValues = #{
"Out-File:Encoding"="utf8";
"Out-File:Append"=$true;
"Out-File:FilePath"=$output
}
This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an email server name or project GUID.
Or put everything inside a function or scriptblock. Note that out-file defaults to utf16 encoding, and can mix encodings, as opposed to add-content.
& {
... collect OS information ...
... collect local users ...
... collect logfile permissions ...
} | add-content $output