从其他Powershell脚本内部运行Powershell脚本,并动态重定向到文件 [英] Run Powershell script from inside other Powershell script with dynamic redirection to file

查看:117
本文介绍了从其他Powershell脚本内部运行Powershell脚本,并动态重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这个问题并进行研究,但无法找到解决方法

I have been struggling with this problem and researching around but can't get a solution

我的问题:我需要从另一个Powershell脚本内部运行一个Powershell脚本,并将输出流重定向到文件.到目前为止,一切都很好. 真正的问题出在我需要通过变量控制日志记录的数量时(例如仅写入错误或仅写入错误+警告+成功输出流).

My problem: I need to run a Powershell script from inside another Powershell script and redirect the output stream to a file. So far so good. The real issue comes when I need to control the amount of logging through a variable (e.g. write only errors or only error + warning + success output streams).

我可以通过如下所示对命令进行硬编码来解决此问题:

I can get around it by hard-coding the command as in:

Powershell -File "\path\myscript.ps1" 2>&1> $logFilePathAndName

但是,我想为用户提供重定向操作符的几个选项,并希望避免对每个选项进行硬编码.为此,我正在考虑只编写类似于以下内容的代码:

However, I want to give the user a couple of options for the redirect operator and want to avoid hardcoding each one of them. For that, I was thinking to just code something similar to :

$logStreams = "2>&1>"
Powershell -File "\path\myscript.ps1" $logStreams $logFilePathAndName

最后一个命令确实运行了我的脚本(myscript.ps1没有输入参数),但是它没有在$logFilePathAndName处向文件写入任何内容.

The last command does run my script (myscript.ps1 has no input params) but it does not write anything to the file at $logFilePathAndName.

我尝试使用Invoke-CommandInvoke-Expression,调用运算符和Powershell -Command的各种语法,但都没有运气.

I tried various syntax with Invoke-Command, Invoke-Expression, the call operator and Powershell -Command with no luck.

查看了 this帖子,尝试了几次,但我不能仅仅让它工作. 例如,这将运行我的脚本,但不会将任何内容写入输出日志:

Looked at this post, had several tries but I can't just get it to work. For example this runs my script but does not write anything to the output log:

$logStreams = "2>&1>"
$command = '"C:\myscript.ps1" $_logStreams "C:\outputlog.txt"'
iex "& $command"

是否有一种方法可以为重定向操作符传递变量字符串,或者运行包含整个命令的字符串,并为输出重定向器插入一个变量?

Is there a way to pass a variable string for the redirect operator OR run a string containing the entire command with a variable interpolated for the output redirector ?

推荐答案

您的最后一位非常接近,但是我不确定为什么在其中有下划线,并且您需要转义美元符号,并用双引号将整个内容括起来以引起字符串外推.

Your last bit there is very close, but I'm not sure why you have the underscore in there, and you need to escape your dollar sign, and close the entire thing in double quotes to cause string extrapolation.

$logStreams = "2>&1>"
$command = "'C:\myscript.ps1' $logStreams 'C:\outputlog.txt'"
iex "& $command"

我刚刚在本地测试过,效果很好.

I just tested that locally and it works fine.

这篇关于从其他Powershell脚本内部运行Powershell脚本,并动态重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆