concept file in category powershell

This is an excerpt from Manning's book Learn PowerShell in a Month of Lunches.
Microsoft’s PowerShell help files are open source materials that are available at https://github.com/MicrosoftDocs/PowerShell-Docs. That can be a good place to see the latest source, which might not yet be compiled into help files that PowerShell can download and display.
You can run that same command on your own, instead of using the > syntax. Why would you do so? Because Out-File also provides additional parameters that let you specify alternative character encodings (such as UTF-8 or Unicode), append content to an existing file, and so forth. By default, the files created by Out-File are 80 columns wide, which means sometimes PowerShell might alter command output to fit within 80 characters. That alteration might make the file’s contents appear different than when you run the same command on the screen. Read Out-File’s help file and see if you can spot a parameter that would let you change the output file width to something other than 80 characters.

This is an excerpt from Manning's book Learn PowerShell Scripting in a Month of Lunches.
Even something as simple as writing information to a CSV file is a single task (and PowerShell has a tool that does that). If you have a script that both produces new information and takes the time to format it as CSV and write it to a file, then you’re not only doing it wrong—you’re working too hard.
Why should you bother with code signing? At its most basic, a signed script authenticates the person who wrote it. This doesn’t mean the script is safe or good to run. But if it’s bad and signed, you can at least track down the author. The other reason for signing is to verify script integrity. In other words, has the code been modified since it was signed? You don’t want a bad actor hijacking your code for their own nefarious goals (although, frankly, if you practice good file security and some common sense, this is a small risk). If you’ve been breached or infected and something or someone can modify an existing script, they could just as easily run their own code. But code integrity means a lot more when you’re sharing code outside your organization. For example, if Jeff sends you a useful script file, or you download one from his blog, how sure are you that every line of code is exactly as Jeff intended? If he signed the file, then you know every character is just what Jeff wrote—and if that code turns out to be malicious, you can track down Jeff and have some words with him about it.
Here’s what the file looks like now:
PS C:\scripts> get-content .\psvm.ps1 get-process | sort vm -desc | select -first 5 # SIG # Begin signature block # MIIFWAYJKoZIhvcNAQcCoIIFSTCCBUUCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUWlS7aTI+/TUJU7Izf4mzM8b1 # HmWgggL6M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nQgRGVjbwIQYcqwRS2cF6ZKK2DM # JNsC6DAJBgUrDgMCGgUAoHgwGAYKKwYBBAGCNwIBDDEKMAigAoAAoQKAADAZBgkq # hkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGC # NwIBFTAjBgkqhkiG9w0BCQQxFgQUsoYetaVPGXeBkFV4ddJTInDikFwwDQYJKoZI # hvcNAQEBBQAEggEARmE9VVlQ+HMYTFnOQ+lJGLvOcm7RKi5+pEVFhxTwoahbu6Zb # oZLEB6zUKx2RxLWkO1+FWiOJWGAAARPnNWCCxBKqAnedtqPNc0UVQ0J5gxuVzfO6 # J5Q+3Uu7YbrbgeErC/hYOMmu9hY8a7H7ttxD0p0qHscV7R1kOSxrUGehU3+KLKFU # heKQlOL26DVGdk3KRayZTGzpDXHavkGAtcjcyiQPSPyRdmFcagdZ4VzrKzTT4m1w # i+uHap5xQ80EQBxfgHZT3yXKRA1tl9Mgnmi9XNcUro25i0tiKZTjkZe0voPJ7MX1 # ePgJFLinSiRvIvzoqpOgN51CfQ/yWWdCsH+v4w== # SIG # End signature blockYou shouldn’t need to mess with the signature block unless you want to completely delete it. That’s the only way to unsign a file.

This is an excerpt from Manning's book Windows PowerShell in Action, Third Edition.
Installation on Windows uses a standard Windows .msi. Download the latest release for your version of Windows from https://github.com/PowerShell/PowerShell/releases. It’ll be named something like PowerShell-6.0.0-beta.3-win10-win2016-x64.msi. After unblocking the file, double-click the .msi and follow the instructions. PowerShell 6.0 installs into C:\Program Files\PowerShell by default. An entry is also created on the Start menu.
The Get-ChildItem cmdlet also has the -Attributes, -Hidden, -ReadOnly, and -System dynamic parameters on the file system provider for dealing with particular file attributes. The file system provider also supports the -Directory and -File dynamic parameters for restricting output to directories and files, respectively.
In PowerShell, files are read using the Get-Content cmdlet. This cmdlet allows you to work with text files using a variety of character encodings and lets you work efficiently with binary files. Writing files is a bit more complex, because you have to choose between Set-Content (or Add-Content) and Out-File. The difference here is whether the output goes through the formatting subsystem.
It’s important to point out that there are no separate open/read/close or open/write/close steps to working with files. The pipeline model allows you to process data and never have to worry about closing file handles—the system takes care of this for you.
You’ve seen that the -TotalCount parameter can be used to control how many lines are read from a file. This parameter has an alias of -Head to fit with other file-reading utilities (Get-Content has aliases of type and cat). Create a file with a number of lines:
PS> 1..10 | foreach { "This is line $_" | Add-Content -Path multifile.txt}You can read the beginning of the file:
PS> Get-Content -Path .\multifile.txt -Head 3

This is an excerpt from Manning's book PowerShell in Depth, Second Edition.
The PowerShell console—but not the ISE currently—supports the Start-Transcript and Stop-Transcript commands. When you start a transcript, every PowerShell command you run, along with its output and errors, will be saved to a text file. Legacy commands such as ping and ipconfig will have the command recorded only in the transcript file, not the output. When you close the shell or stop the transcript, the shell stops recording your actions. If you run Start-Transcript without any parameters, it creates a file in your Documents folder that includes a timestamp. Or you can specify your own filename:
PS C:\> Start-Transcript c:\work\Monday.txtYou’ll find transcripts useful when you’re experimenting with the shell, because they enable you to keep a log of everything you’ve tried. You can then review the file in Notepad or another text editor, copy out the parts you want, and save them for future use. If necessary, you can append to an existing transcript file. This can be handy when you’re working with PowerShell features that can exist between PowerShell sessions, such as workflows. Use the –append parameter:
PowerShell v3 introduced a new feature called updatable help. This is a great feature that has, unfortunately, led to a lot of confusion and gnashing of teeth. For a number of reasons, both technical and nontechnical, Microsoft doesn’t include any of PowerShell’s help files with PowerShell itself. Instead, you must download and install those help files on any computer where you’ll want to read them. To do so, run Update-Help. The command can even download updated help for non-Microsoft shell extensions that have been designed to take advantage of this feature. You should also set yourself a reminder to run it every month or so in order to have the most recent help files on your system, possibly as a scheduled job using another feature introduced in PowerShell v3 (see chapter 11). You can also subscribe to an RSS feed at http://sxp.microsoft.com/feeds/msdntn/PowerShellHelpVersions that will provide information when new versions of the help files are made available. If you don’t download help, you’ll be prompted to do so the first time you use the Get-Help cmdlet.
PS C:\> help filesystem PROVIDER NAME FileSystem DRIVES C, D SYNOPSIS Provides access to files and directories. DESCRIPTION The Windows PowerShell FileSystem provider lets you get, add, change, clear, and delete files and directories in Windows PowerShell. The FileSystem provider exposes Windows PowerShell drives that correspond to the logical drives on your computer, including drives that are mapped to network shares. This lets you reference these drives from within Windows PowerShell.
In addition to providing help on commands, PowerShell includes help for general concepts, troubleshooting, and so forth. Usually referred to as “about” files because their filenames start with the word “about,” these files act as PowerShell’s formal documentation. To see a complete list you can run the command yourself, but we’ll truncate it as follows:

This is an excerpt from Manning's book PowerShell Deep Dives.
PS > Get-Counter -ListSet *disk* CounterSetName : LogicalDisk MachineName : . CounterSetType : MultiInstance Description : The Logical Disk performance object consists of counters that monitor logical partitions of a hard or fixed disk drives. Performance Monitor identifies logical disks by their a drive letter, such as C. Paths : {\LogicalDisk(*)\% Free Space, \LogicalDisk(*)\Free Megabytes, \LogicalDisk(*)\Current Disk Queue Length, \LogicalDisk(*)\% Disk Time...} PathsWithInstances : {\LogicalDisk(E:)\% Free Space, \LogicalDisk(C:)\% Free Space, \LogicalDisk(_Total)\% Free Space, \LogicalDisk(E:)\Free Megabytes...} Counter : {\LogicalDisk(*)\% Free Space, \LogicalDisk(*)\Free Megabytes, \LogicalDisk(*)\Current Disk Queue Length, \LogicalDisk(*)\% Disk Time...} CounterSetName : PhysicalDisk MachineName : . CounterSetType : MultiInstance Description : The Physical Disk performance object consists of counters that monitor hard or fixed disk drive on a computer. Disks are used to store file, program, and paging data and are read to retrieve these items, and written to record changes to them. The values of physical disk counters are sums of the values of the logical disks (or partitions) into which they are divided. Paths : {\PhysicalDisk(*)\Current Disk Queue Length, \PhysicalDisk(*)\% Disk Time, \PhysicalDisk(*)\Avg. Disk Queue Length, \PhysicalDisk(*)\% Disk Read Time...} PathsWithInstances : {\PhysicalDisk(0 E: C:)\Current Disk Queue Length, \PhysicalDisk(_Total)\Current Disk Queue Length, \PhysicalDisk(0 E: C:)\% Disk Time, \PhysicalDisk(_Total)\% Disk Time...} Counter : {\PhysicalDisk(*)\Current Disk Queue Length, \PhysicalDisk(*)\% Disk Time, \PhysicalDisk(*)\Avg. Disk Queue Length, \PhysicalDisk(*)\% Disk Read Time...}
The Get-Content cmdlet retrieves text from a file and creates an array of strings (as opposed to one long string with line breaks). Each string is one line from the original file.

This is an excerpt from Manning's book PowerShell in Practice.
Table 1.3. Utility cmdlets and their purposes
Utility cmdlet
Alias
Purpose
Compare-Object Compare or diff Compares two sets of objects. ForEach-Object Foreach or % Performs an operation against each of a set of input objects. Group-Object Group Groups objects that contain the same value for specified properties. Measure-Object Measure Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text. Select-Object Select Selects specified properties of an object or set of objects. It can also select unique objects from an array of objects, or it can select a specified number of objects from the beginning or end of an array of objects. Sort-Object Sort Sorts objects by property values Tee-Object Tee Saves command output in a file or variable and displays it in the shell. Where-Object Where or ? Creates a filter that controls which objects will be passed along a command pipeline.
PowerShell provides several ways to create and write to a file, as shown in listing 8.6. The best one to use depends on circumstances. One of the great strengths of PowerShell is that there are multiple ways to achieve a goal. This can also be perceived as a weakness, especially by someone setting out to learn PowerShell. The best advice I can give is to look at the alternatives and settle on which works best in your particular circumstances. This may well involve experimentation. Never be afraid to experiment—that’s why you can use the same commands from the prompt as in your scripts!
Listing 8.6. Creating files
New-Item -Name testfile.txt -Path c:\scripts\testfolder -ItemType File -Value "This is a one line file" Get-Service | Out-File -FilePath c:\scripts\testfolder\sp.txt Get-Process | Out-File -FilePath c:\scripts\testfolder\sp.txt -Append Get-Process | Export-Csv -Path c:\scripts\testfolder\testprc.csv -NoTypeInformationWe can use New-Item to create a file
. We follow the same pattern as when creating a folder, and supply the name, the path, and the type of item we’re creating. We also have the option to add content to the file at the time of creation by using the -value parameter. If this is omitted, an empty file is created, as in the examples in chapter 2. The Set-Content cmdlet can be used to put content into the empty file. If it’s used against a file that already has content, that content will be overwritten. This option is good if we need to create an empty file or we have content available to write to the file as one piece.
Our second option involves using Out-File
. In the first part of the script, we pipe the results from using Get-Service into our file. The second part appends the results of Get-Process. Note the use of the -Append parameter. This forces the data to be appended to the end of the file rather than overwriting the file contents, which is the default behavior. One of the best uses of Out-File is where we need to keep appending data to a file. Add-Content can also be used to append data to a file.
The final option is to use Export-Csv
. A text file was produced in the previous two cases. In this example, we’re creating a delimited file where the fields are separated by commas. We need to give the path to the file pipe in the data we wish to write into the file. The -NoTypeInformation parameter prevents the .NET type information from being written into the first row of the file. We don’t usually need this information, so it’s best to use this parameter as a matter of routine.
Get-Content can be used to read the contents of a file
. One source of error in our scripts is that the file we’re trying to use isn’t actually present. We can avoid this by using Test-Path as shown. This cmdlet returns $true if it finds the file and $false if it doesn’t. Performing this test allows us to avoid the error.
The best way to read a .csv file is to use Import-Csv
. The great thing about this approach is that the field names in the header row in the file can be used in the script after the file has been read. This can either be in a select statement as here or referred to as $_.fieldname when appropriate; for example in a foreach cmdlet. Examples of this will appear throughout the book.
When using Get-Content or Import-Csv, it’s often desirable to read the contents of the file into a variable. Script
would become:
$data = Import-Csv -Path c:\scripts\testfolder\testprc.csv
$data | Select Name, PeakPagedMemorySize,
PeakWorkingSet, PeakVirtualMemorySize |
Format-Table -AutoSizeWe could use the same variable in a number of subsequent statements. This approach is worth adopting if you’ll be performing a number of actions on the data. It saves the overhead of rereading the file.
These examples show how we can use pieces of PowerShell functionality to read the contents of a file. One other scenario we need to think about is how we search a set of files to find the one that contains the data in which we’re interested.
. We follow the same pattern as when creating a folder, and supply the name, the path, and the type of item we’re creating. We also have the option to add content to the file at the time of creation by using the -value parameter. If this is omitted, an empty file is created, as in the examples in
. In the first part of the script, we pipe the results from using Get-Service into our file. The second part appends the results of Get-Process. Note the use of the -Append parameter. This forces the data to be appended to the end of the file rather than overwriting the file contents, which is the default behavior. One of the best uses of Out-File is where we need to keep appending data to a file. Add-Content can also be used to append data to a file.
. A text file was produced in the previous two cases. In this example, we’re creating a delimited file where the fields are separated by commas. We need to give the path to the file pipe in the data we wish to write into the file. The -NoTypeInformation parameter prevents the .NET type information from being written into the first row of the file. We don’t usually need this information, so it’s best to use this parameter as a matter of routine.