the*_*ent 3 arrays parameters powershell scheduled-tasks
我创建了一个PowerShell脚本,可以从Management Shell中完美运行.我试图把它安装在Windows Server 2008 R2的计划任务工作,我不能确定如何通过我的字符串数组参数的参数.
这是我的脚本的相关部分:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]
$BaseDirectory,
[String]
$BackupMethod = "Full",
[Int]
$RemoveOlderThanDays = 0,
[String]
$LogDirectory,
[Int]
$LogKeepDays = 7,
[String[]]
$AdditionalDirectories
)
if ($AdditionalDirectories -and $AdditionalDirectories.Count -gt 0) {
Write-Host " Additional Directories to be included:" -ForegroundColor Green
$AdditionalDirectories | ForEach-Object {
Write-Host " $_" -foregroundcolor green
}
}
Run Code Online (Sandbox Code Playgroud)
给出麻烦的参数是最后一个,$AdditionalDirectories.
如果我像这样从Management Shell运行脚本,它可以很好地工作:
.\FarmBackup.ps1 \\SomeServer\Backups Full 0 D:\Logs\Backups 0 "D:\Documents\PowerShell Scripts","D:\SomeFolder"
Run Code Online (Sandbox Code Playgroud)
结果:
Additional Directories to be included:
D:/Documents/PowerShell Scripts
D:/SomeFolder
Run Code Online (Sandbox Code Playgroud)
行动: 启动一个程序
程序/脚本: PowerShell.exe
参数: -File"D:\ Documents\PowerShell Scripts\FarmBackup.ps1"\\ SomeServer\Backups Full 0 D:\ Logs\Backups 0"D:\ Documents\PowerShell Scripts","D:\ SomeFolder"
结果:(来自日志文件)
Additional Directories to be included:
D:\Documents\PowerShell Scripts,D:\SomeFolder
Run Code Online (Sandbox Code Playgroud)
我已经为这些参数尝试了几种不同的方法,但我似乎无法将它们视为字符串数组中的两个单独的字符串.我现在正在对它们进行硬编码,但似乎必须有一种方法可以使这个工作,因为它从shell运行时完全有效.
尝试使用-Command开关而不是-File开关,然后使用调用运算符'&'.以下是使用计划任务执行此操作的示例的链接:
就像是:
-Command "& 'D:\Documents\PowerShell Scripts\FarmBackup.ps1' '\\SomeServer\Backups' 'Full' 0 'D:\Logs\Backups' 0 'D:\Documents\PowerShell Scripts','D:\SomeFolder'"
Run Code Online (Sandbox Code Playgroud)
我通过创建包含内容的脚本来测试此解决方案:
param([string[]] $x)
Write-Host $x.Count
Run Code Online (Sandbox Code Playgroud)
然后通过以下两种方式调用它:
powershell -File ".\TestScript.ps1" "what1,what2"
Run Code Online (Sandbox Code Playgroud)
结果:1
和
powershell -Command "& .\TestScript.ps1 what1,what2"
Run Code Online (Sandbox Code Playgroud)
结果:2