点源脚本在第二次运行时未引用当前目录

时间:2018-08-22 04:41:53

标签: powershell command-prompt

我在下面有一个脚本,该脚本在Scripts文件夹中。它引用了一组命令提示符应用程序$cmd1.exe, etc.。使用VS Code中的Powershell或Integrated Powershell终端,我按照以下步骤使用它:

  1. 不要从脚本目录> .\new-customconfig.ps1中获取脚本,
  2. 切换到工作目录> cd [New Directory]
  3. 使用脚本中的函数并从工作目录> New-CustomConfig .\FileName中传递文件名。

当我第一次运行脚本时,它将从工作目录传递文件,但是随后的运行中,它将在Scripts目录中查找文件。

我在做错什么吗?

Function New-CustomConfig {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]
        $FileName
    )

    Begin {
        #Set tools directory
        $ToolD = '[Directory]\Tools'

        #Clean up filename
        $FileName = $FileName -replace '^[\W]*', ''

        #Setup Executables
        $cmdtools = "\cmd1.exe", "\cmd2.exe", "\cmd3.exe"

        #Setup Arguments
        $cmdargs = "cmd1args", "cmd2args", "cmd3args"

        #Setup Write-Host Comments
        $cmdecho = "echo1", "echo2", "echo3"

        #Setup command object info
        $cmdinfo = New-Object System.Diagnostics.ProcessStartInfo
        $cmdinfo.RedirectStandardError = $true
        $cmdinfo.RedirectStandardOutput = $true
        $cmdinfo.UseShellExecute = $false

        #Create command object
        $cmd = New-Object System.Diagnostics.Process

        "Generating Config for $FileName"
    }

    Process {
        for ($i = 0; $i -le $cmdtools.Count; $i++) {
            $cmdinfo.FileName = $ToolD + $cmdtools[$i]
            $cmdinfo.Arguments = '' + $cmdargs[$i] + ''
            Write-Host $i
            Write-Host $cmdinfo.FileName
            Write-Host $cmdinfo.Arguments
            Write-Host $(Get-Location)

            $cmdecho[$i]

            $cmd.StartInfo = $cmdinfo
            $cmd.Start() | Out-Null
            $cmd.WaitForExit()

            $stdout = $cmd.StandardOutput.ReadToEnd()
            $stderr = $cmd.StandardError.ReadToEnd()

            Write-Host "stdout: $stdout"
            Write-Host "stderr: $stderr"
            Write-Host "exit code: " + $p.ExitCode
        }
    }

    End {
        "Press any key to continue..."
        $null = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    }

}

0 个答案:

没有答案