简体   繁体   English

Powershell从文件传递命名参数

[英]Powershell passing named parameters from file

i have a problem that is troubling my mind. 我有一个困扰我的问题。

I want to automatically execute powershell scripts with named arguments but within another powershell script (that will act as a script deamon). 我想使用命名参数自动执行Powershell脚本,但要在另一个Powershell脚本(将其作为脚本守护程序)中执行。

For example: 例如:

One of the scripts that get called has this parameters 被调用的脚本之一具有此参数

param(
[int]$version,
[string]$user,
[string]$pass,
[string]$domain,

)

The powershell script deamon now loads the file and arguments like this 现在,powershell脚本守护进程将像这样加载文件和参数

$argumentsFromScript = [System.IO.File]::ReadAllText("C:\params.txt") $job = Start-Job { & "ps1file" $arguments} 

The params.txt contains the data like this params.txt包含这样的数据

-versionInfo 2012 -user admin -pass admin -domain Workgrup

But when i try to execute this code obviously the whole $argumentsFromScript variable will be seen as parameter 1 (version) and i end up with an error, that "-versionInfo 2012 -user admin -pass admin -domain Workgrup" cannot be converted to Int32... 但是,当我尝试执行此代码时,显然整个$ argumentsFromScript变量将被视为参数1(版本),并且最终出现错误,无法将“ -versionInfo 2012 -user admin -pass admin -domain Workgrup”转换为INT32 ...

Do you guys have any idea how i can accomplish this task? 你们知道我如何完成这项任务吗? The Powershell deamon does not know anything about the parameters. Powershell守护程序对参数一无所知。 He just needs to execute scripts with given named parameters. 他只需要使用给定的命名参数执行脚本即可。 The params.txt is just an example. params.txt只是一个示例。 Any other file (csv,ps1,xml,etc) would be fine, i just want to automatically get the named parameters passed to the script. 任何其他文件(csv,ps1,xml等)都可以,我只想自动获取传递给脚本的命名参数。

Thank you in advance for any help or advice.. 预先感谢您的任何帮助或建议。

Try this: 尝试这个:

@'
param ([string]$logname,[int]$newest)
get-eventlog -LogName $logname -Newest $newest
'@ | sc c:\testfiles\testscript.ps1

 '-logname:application -newest:10' | sc c:\testfiles\params.txt

$script = 'c:\testfiles\testscript.ps1'
$arguments = 'c:\testfiles\params.txt'

$sb = [scriptblock]::Create("$script $(get-content $argumentlist)")

Start-Job -ScriptBlock $sb

I guess you want this: 我猜你想要这个:

$ps1 = (Resolve-Path .\YourScript.ps1).ProviderPath
$parms = (Resolve-Path .\YourNamedParameters.txt).ProviderPath

$job = sajb -ScriptBlock {
    param($ps1,$parms) 
    iex "$ps1 $parms"
} -ArgumentList @(
    $ps1,
    [string](gc $parms)
)

# if you wanna see the outcome
rcjb $job -Wait

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM