我已经创建了一个PowerShell脚本,但出于某种原因,“启动进程”-cmdlet似乎没有正确运行。这是我的代码:
[string]$ListOfProjectFiles = "project_file*."
[string]$arg = "project_file"
[string]$log = "C:\Work\output.log"
[string]$error = "C:\Work\error.log"
Get-ChildItem $PSScriptRoot -filter $ListOfProjectFiles | `
ForEach-Object {
[string]$OldFileName = $_.Name
[string]$Identifier = ($_.Name).Substring(($_.Name).LastIndexOf("_") + 1)
Rename-Item $PSScriptRoot\$_ -NewName "project_file"
Start-Process "$PSScriptRoot\MyExecutable.exe" ` #This line causes my headaches.
-ArgumentList $arg `
-RedirectStandardError $error `
-RedirectStandardOutput $log `
-Wait
Remove-Item "C:\Work\output.log", "C:\Work\error.log"
Rename-Item "$PSScriptRoot\project_file" -NewName $OldFileName
}主要问题是,程序在我的机器上运行,但只在我添加了-Wait开关之后。我发现,如果我在PowerShell-ISE中遍历我的代码,MyExecutable.exe 确实识别了参数并正确运行了程序,而如果我只是运行没有断点的脚本,它就会出错,就好像它无法解析$arg值一样。添加-Wait开关似乎解决了我的机器上的问题。
在我的同事的机器上,MyExecutable.exe不识别-ArgumentList $arg部件的输出:它只是终止了一个错误,说明找不到所需的参数(应该是"project_file")。
我尝试过对"project_file"部分进行硬编码,但这没有成功。我也一直在玩Start-Process-cmdlet的其他开关,但是没有什么工作。我有点不知所措,对PowerShell非常陌生,但我完全搞不懂为什么它在不同的计算机上的行为不同。
我做错了什么?
发布于 2015-06-09 09:49:07
如果不使用-Wait开关,则脚本继续运行,而MyExecutable.exe仍在执行。特别是,您可以在编程之前重命名文件(Rename-Item "$PSScriptRoot\project_file" -NewName $OldFileName),然后打开它。
将普通的project_file作为参数传递给程序。如果当前工作目录不是$PSScriptRoot怎么办?除了/而不是当前的工作目录之外,MyExecutable.exe是否设计用于查找exe位置目录中的文件?我建议提供完整路径,而不是:
[string]$arg = "`"$PSScriptRoot\project_file`""不要仅仅将FileInfo或DirectoryInfo对象转换为字符串。它不能保证返回完整的路径或只返回文件名。显式地请求Name或FullName属性值,这取决于您想要什么。
Rename-Item $_.FullName -NewName "project_file"https://stackoverflow.com/questions/30726692
复制相似问题