Question

I like F# and I want to practice a little by writing some scripts for automation of some annoying task.

How do i interact with other programs the same way i can do from CMD or PowerShell for example RoboCopy or iisreset or net?

I know i can do it myself with System.Diagnostics.Process but it's difficult to do right (return codes, standard streams, etc.) .

There has to be a library for this, any suggestions?

Was it helpful?

Solution

You want to use the System.Management.Automation namespace. Here's an example of running some cmdlets from F#.

// C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0
open System.Management.Automation
open System.Management.Automation.Runspaces;

let runSpace = RunspaceFactory.CreateRunspace()
runSpace.Open()
let pipeline = runSpace.CreatePipeline()

let getProcess = new Command("Get-Process")
pipeline.Commands.Add(getProcess)

let sort = new Command("Sort-Object")
sort.Parameters.Add("Property", "VM")
pipeline.Commands.Add(sort)

// Identical to the following PowerShell command line:
// PS > Get-Process | Sort-Object -Property VM | select ProcessName

let output = pipeline.Invoke()
for psObject in output do
    psObject.Properties.Item("ProcessName").Value.ToString()
    |> printfn "%s"

You can also build cmdlets with F# and use PowerShell to move data. Check out this post on the Visual Studio F# Team Blog. It's a good example on how to write a Cmdlet in F#. You can also embed F# into PowerShell but in general it's better to make Cmdlets.

Cmdlet MSDN reference
Scripting with Windows PowerShell

OTHER TIPS

Fake has an ExecProcess task that might help. Also you could look at the Fake source for more ideas.

If you use the Developer Command Prompt for VS2012 (available under the Start Menu -> Programs -> Microsoft Visual Studio 2012 -> Visual Studio Tools), you'll have fsi (F# Interactive) in the path already. For example:

C:\Program Files (x86)\Microsoft Visual Studio 11.0>fsi

Microsoft (R) F# Interactive version 11.0.60315.1
Copyright (c) Microsoft Corporation. All Rights Reserved.

For help type #help;;

> #quit;;

C:\Program Files (x86)\Microsoft Visual Studio 11.0>

You can create F# script files -- they use the *.fsx file extension -- and then run them using fsi. Under Mono on OSX, FreeBSD, and Linux, you can also add a "shebang" to *.fsx files and run them just like you would a Python, Perl, etc. script.

EDIT: As far as running the external programs, there are some libraries on NuGet for simplifying this -- cmd is the first one I found. It's for C#, but it should be straightforward to implement some wrapper functions to make it easier to consume from F#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top