Skip to main content

Creating files with powershell

powershell



There comes a time when you need to create files with powershell. Search the web and you will find many solutions. Here I am going to list a few of you options.








First one up is from the Powershell Magazine by Shay Levy:
image

It is a basic functions with some parameters for you to change the path where the file should be written and the size of the file.

Second is from another blog Nate Jones. It is a couple of lines with code for you to run:

image

Third is from Jeffery Hicks. He also use the [IO.File] .Net class to create an advanced function that also supports pipeline input. His function requires Powershell version 4:

image

Click the pictures to find the article about each solution. If you search for your self, you will see pretty much all kinds of variations around the .Net class System.IO.File. Natively in Powershell to my knowledge there is no single cmdlet that lets you create files of an predefined size. So lets dig around and see what we can find.

First we need to discuss the size. Size can be specified in bytes, kilobytes(kb), megabytes(mb), gigabytes(gb) and so on. Lucky for us powershell know about this. So if I need to know how many bytes there is in 1 megabyte, I can just ask powershell by typing the command 1mb:

image

This also works with calculus, so if I type this:

image 

Powershell will print the letter "a" 1024 times because there is 1024 bytes in 1kb. Now we can create “content” of a specific size. All we need now is to find some way of writing this to a file.

Two cmdlets come to mind: Out-File and Set-Content. There is also Add-Content, however that is for appending contents to a file.

First candidate Out-File:

image

We can se that we can create files with this function. We just need to specify a path (FilePath) and an InputObject (the value/content we want the file to have). Lets try to create a file of 10kb:

image

There, the file was created and the size was 20486 bytes. Strange that is more than 10kb, actually it is twice the size we were looking for. Notice in the help information we have a parameter called Encoding. Maybe we need to set the encoding to something, oh we can use UTF8 perhaps:

 image

That is better, pretty close to 10kb. I mentioned Set-Content cmdlet, we should give that one a go as well:

image

Well there you go, even easier to remember, no need to worry about encoding. Set-Content got it right the first time. I prefer to write it like this:

image

First I pick a size and pipe that to the Set-content cmdlet and chose the path and filename.

If speed is a requirement, you are probably best off doing file creation with the .Net class System.IO.File. Any of the functions I mentioned earlier will do that just fine. On my system, creating a 10mb file took 79ms using Set-Content cmdlet. If I use Jeffery’s function it takes about 20ms to create a file. Not a huge difference unless you want to create really huge files or may of them.

Cheers

Tore

Comments

Popular posts from this blog

Serialize data with PowerShell

Currently I am working on a big new module. In this module, I need to persist data to disk and reprocess them at some point even if the module/PowerShell session was closed. I needed to serialize objects and save them to disk. It needed to be very efficient to be able to support a high volume of objects. Hence I decided to turn this serializer into a module called HashData. Other Serializing methods In PowerShell we have several possibilities to serialize objects. There are two cmdlets you can use which are built in: Export-CliXml ConvertTo-JSON Both are excellent options if you do not care about the size of the file. In my case I needed something lean and mean in terms of the size on disk for the serialized object. Lets do some tests to compare the different types: (Hashdata.Object.ps1) You might be curious why I do not use the Export-CliXML cmdlet and just use the [System.Management.Automation.PSSerializer]::Serialize static method. The static method will generate t

Toying with audio in powershell

Controlling mute/unmute and the volume on you computer with powershell. Add-Type -TypeDefinition @' using System.Runtime.InteropServices; [Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IAudioEndpointVolume { // f(), g(), ... are unused COM method slots. Define these if you care int f(); int g(); int h(); int i(); int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext); int j(); int GetMasterVolumeLevelScalar(out float pfLevel); int k(); int l(); int m(); int n(); int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext); int GetMute(out bool pbMute); } [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IMMDevice { int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev); } [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), Inte

Creating Menus in Powershell

I have created another Powershell module. This time it is about Console Menus you can use to ease the usage for members of your oranization. It is available on GitHub and published to the PowershellGallery . It is called cliMenu. Puppies This is a Controller module. It uses Write-Host to create a Menu in the console. Some of you may recall that using Write-Host is bad practice. Controller scripts and modules are the exception to this rule. In addition with WMF5 Write-Host writes to the Information stream in Powershell, so it really does not matter anymore. Design goal I have seen to many crappy menus that is a mixture of controller script and business logic. It is in essence a wild west out there, hence my ultimate goal is to create something that makes it as easy as possible to create a menu and change the way it looks. Make it easy to build Menus and change them Make it as "declarative" as possible Menus The module supports multiple Men