Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function Split-Command {
- <#
- .SYNOPSIS
- Split a command string into a ShellCommand class object.
- .DESCRIPTION
- Splits a command into an object consisting of the file path and an argument array.
- .PARAMETER Command
- The command string to split.
- .INPUTS
- System.String
- A string object or string array may be piped into this command.
- .OUTPUTS
- ShellCommand
- Returns a custom class object consisting of the file path and an array of arguments, as well as a method to execute the command.
- - FilePath
- - Arguments
- - Execute([[boolean]<wait>][, [boolean]<runas>])
- .EXAMPLE
- Split-Command -Command """${env:ProgramFiles}\Internet Explorer\iexplore.exe"" -no-first-run ""https://www.example.com"""
- #>
- [CmdletBinding(DefaultParameterSetName = "ByParameter")]
- Param(
- [Parameter(Mandatory = $true, ParameterSetName = "ByParameter", ValueFromPipeline = $true)]
- [ValidateNotNullOrEmpty()]
- [String[]]$Command
- )
- Begin {
- Class ShellCommand {
- [String]$FilePath
- [String[]]$Arguments
- ShellCommand() {}
- ShellCommand([String]$FilePath) {
- $this.FilePath = $FilePath
- $this.Arguments = $null
- }
- ShellCommand([String]$FilePath, [String[]]$Arguments) {
- $this.FilePath = $FilePath
- $this.Arguments = $Arguments
- }
- [Int32]Execute([boolean]$Wait,[boolean]$RunAs) {
- $proc = New-Object -TypeName System.Diagnostics.Process
- $proc.StartInfo.FileName = $this.FilePath
- $proc.StartInfo.Arguments = "$($this.Arguments)"
- $proc.StartInfo.UseShellExecute = $false
- Switch ($RunAs) {
- $true { $proc.StartInfo.Verb = 'runas'; break }
- Default { $proc.StartInfo.Verb = 'open' }
- }
- $proc.Start()
- If ($Wait) {
- Do {} Until ($proc.HasExited)
- }
- return $proc.ExitCode
- }
- [Int32]Execute([boolean]$Wait) {
- return $this.Execute($Wait,$false)
- }
- [Int32]Execute() {
- return $this.Execute($true,$false)
- }
- }
- [ShellCommand[]]$retval = $null
- [String]$rgxProgPattern = '(?<=.*(?:\.exe|\.cmd|\.bat|rundll32)["]?) +'
- [String]$rgxArgsPattern = ' +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)'
- }
- Process {
- [String[]]$strArray = $Command -split $rgxProgPattern,2
- Write-Debug "strArray[0] = $($strArray[0])`nstrArray[1] = $($strArray[1])"
- [String]$FilePath = $strArray[0]
- [String[]]$ArgArray = ($strArray[1] -split $rgxArgsPattern)
- $retval += New-Object -TypeName ShellCommand -ArgumentList @($FilePath,$ArgArray)
- }
- End {
- return $retval
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement