How do I write a script that opens an iTerm2 window and runs a command?

Try this:

tell application "iTerm2"
    set newWindow to (create window with default profile)
    tell current session of newWindow
        write text "echo it works!"
    end tell
end tell

The write command, when not using without newline, executes the write text command because of the default added newline after the "text to send". Thus the window stays open after the command completes, ready for additional use.


From the iTerm AppleScript Dictionary:

writev : Send text as though it was typed.

      write specifier : The session to send to
            [contents of file file] : Filename to send the contents of
            [text text] : Text to send
            [newline boolean] : If newline should be added to end of text (default: yes)