我试图通过任务计划程序每天运行PowerShell脚本,但脚本不会运行。当我手动将下面的代码输入PowerShell(作为管理员)时,它会让我按两次输入。我相信,因为我必须按两次输入是它不会通过任务调度程序的原因。
有没有办法调整我的代码以使其与任务调度程序一起使用?
我正在运行Windows 2012 R2和PowerShell的5.1版。
请注意,我在我的计算机上运行完全相同的脚本,即Windows 10并运行PowerShell版本5.1,并且它以正确的方式运行(只需按一次输入)
我希望只按一次输入运行我的PowerShell脚本,但是第一次按Enter键的实际输出带来另一行只有“>>”,然后我按第二次输入并执行脚本。
Powershell脚本:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = ""
UserName = ""
Password = ""
SshHostKeyFingerprint = ""
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Transfer files
$session.PutFiles("", "").Check()
}
finally
{
$session.Dispose()
}
如果脚本需要用户交互,那么它实际上不应该是计划任务。
如果编写需要确认的脚本,则需要使用-Confirm参数查看。
见Are you sure? Using the -WhatIf and -Confirm parameters in PowerShel
Remove-MailContact -Identity“$ sourceEmail”-Confirm:$ Y -WhatIf
您编写的cmdlet或代码必须支持它。对于您编写的代码,这意味着使用advanced functions。
How to write a PowerShell function to use Confirm, Verbose and WhatIf
function Set-FileContent
{
[cmdletbinding(SupportsShouldProcess)]
Param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Content,
[Parameter(Mandatory = $true)]
[ValidateScript( {Test-Path $_ })]
[string]$File
)
if ($PSCmdlet.ShouldProcess("$File" , "Adding $Content to "))
{
Set-Content -Path $File -Value $Content
}
}