3

我有一个 .net 应用程序,它成功运行从文本文件中提取的 Powershell 命令,直到我尝试执行一个更复杂且包含 if 条件的命令。该脚本可以在 PS 控制台上正常工作,但在 .NET 中,我只知道如何为脚本传递一个字符串,在读取文件后,它会添加额外的东西,例如 vblf,即使我把它拿出来,它也不会工作. 这甚至可能吗?

.NET 运行时错误:服务器无法处理请求。---> 术语“False”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

.NET 代码:

'Grab Powershell script from text (.ps1) file
strScript = File.ReadAllText(ScriptFileName)

'inject the arguments into the script
strScript = InsertArguments(strScript, Arguments)

'Open the runspace and create a pipeline if it's not already open
If psRunspace.RunspaceStateInfo.State = RunspaceState.BeforeOpen Then
  psRunspace.Open()
End If

Dim MyPipeline As Pipeline = psRunspace.CreatePipeline()
MyPipeline.Commands.AddScript(strScript)
Dim psResults As Collection(Of PSObject) = MyPipeline.Invoke()

Powershell 脚本,存储在 ps1 文件中:

new-mailbox -name $argument1 -DisplayName $argument1 -UserPrincipalName $argument2 Room -DomainController $argument5
if ($argument4 -eq "False") {
   Set-CalendarProcessing $argument1 -BookingWindowInDays 400 -DeleteSubject $false -AutomateProcessing autoaccept -AllBookInPolicy $false -BookInPolicy $argument3 -DomainController $argument5        
} else {
   Set-CalendarProcessing $argument1 -BookingWindowInDays 400 -DeleteSubject $false -AutomateProcessing autoaccept -AllBookInPolicy $true -DomainController $argument5
}

当这个脚本被读入时,这里是一个被拉入的子字符串strScript

-Room -DomainController mcexdct1" & vbLf & "if (False -eq "False") {"
4

1 回答 1

2

Fixed it by changing the PowerShell script from this:

if ($argument4 -eq "False") {

to this:

if ("$argument4" -eq "False") {

It works with quotation marks around it. I guess the "junk" I was seeing in the script string (like vblf) is normal- I don't work with reading from text files that much.

于 2013-02-28T18:29:30.417 回答