我正在编写我的第一个Powershell脚本并且来自C#很困惑,我的代码如下:
function Run(
[string] $command,
[string] $args,
[Ref] [string] $stdout,
[Ref] [string] $stderr
)
{
$p1 = New-Object System.Diagnostics.Process
$p1.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$p1.StartInfo.FileName = $command
$p1.StartInfo.Arguments = $arguments
$p1.StartInfo.CreateNoWindow = $true
$p1.StartInfo.RedirectStandardError = $true
$p1.StartInfo.RedirectStandardOutput = $true
$p1.StartInfo.UseShellExecute = $false
$p1.Start()
$p1.WaitForExit()
}
$p = New-Object System.Diagnostics.Process
$p.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$p.StartInfo.FileName = "ping"
$p.StartInfo.Arguments = "142.553.22242.2"
$p.StartInfo.CreateNoWindow = $true
$p.StartInfo.RedirectStandardError = $true
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.UseShellExecute = $false
$p.Start()
$p.WaitForExit()
$code = $p.ExitCode
$stderr = $p.StandardError.ReadToEnd()
$stdout = $p.StandardOutput.ReadToEnd()
Run("ping","208.67.222.222","","")
$ p.Start()有效,但由于某种原因,传入Run函数的参数被忽略,$ p1失败。我做错了什么?
Exception calling "Start" with "0" argument(s): "The system cannot find the file specified"
At C:\Users\Administrator\Desktop\logtofile.ps1:27 char:5
+ $p1.Start()
+ ~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : Win32Exception
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\Users\Administrator\Desktop\logtofile.ps1:28 char:5
+ $p1.WaitForExit()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
答案 0 :(得分:4)
我没有尝试从函数内部启动一个进程,但是我得到了同样的错误。我花了几分钟才意识到这是我最喜欢的浪费时间之一:UAC陷阱。我没有使用"以管理员身份运行"来启动PowerShell。您必须具有管理员权限并运行代码才能启动/停止/修改您不拥有的进程,并且此错误消息在这方面完全没有帮助。
答案 1 :(得分:3)
您必须按如下方式调用run:
Run "ping","208.67.222.222","",""
放入括号之间将其作为单个数组参数传递给函数。
答案 2 :(得分:0)
class AboutView(TemplateView):
template_name = "about.html"
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(publish_date__lte=timezone.now()).order_by('-publish_date')
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blogapp/post_detail.html'
model = Post
form_class = PostForm
def get_queryset(self):
class PostUpdateView(LoginRequiredMixin, UpdateView):
login_url = '/login/'
redirect_field_name = 'blogapp/post_detail.html'
model = Post
form_class = PostForm
class PostDeleteView(LoginRequiredMixin, DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin, ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(publish_date__isnull=True).order_by('create_date')
答案 3 :(得分:0)
我在服务上的 start() 函数中遇到此错误,因为一位同事在 Windows 服务窗口中将该服务设置为“已禁用”。将其设置回“手动”修复了它。