首页 文章

使用计划的Powershell脚本调用URL

提问于
浏览
8

我只想在Windows Server 2008和Powershell脚本上调用带有任务调度程序的URL .

所以我开发了以下脚本:

$url = "http://example.com"

$log_file = "${Env:USERPROFILE}\Desktop\Planification.log"
$date = get-date -UFormat "%d/%m/%Y %R"
"$date [INFO] Exécution de $url" >> $log_file

$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
$response.Close()

当我从Powershell ISE,Powershell控制台或使用命令执行它时,该脚本没有任何问题:

powershell PATH_TO_MY_SCRIPT.ps1

但是当我从Scheduler任务执行它时它不起作用,它返回代码0xFFFD0000 . 我发现了这个:http://www.briantist.com/errors/scheduled-task-powershell-0xfffd0000/所以它可能是一个权限问题,所以我尝试了很多其他配置文件和选项(包括"Execute with all permissions")来测试,但没有成功 .

我还执行另一个Powershell脚本,它只挂载一个网络驱动器并复制两个文件,我对这个脚本没有任何问题 . 所以我认为问题来自使用.NET对象来调用我的URL .

我看到在任何其他命令之前我可能必须在我的脚本中包含模块,但我不确切知道我必须做什么 . (我不知道Powershell,我只是试着用它来解决我的问题) .

谢谢你的帮助 .

3 回答

  • 1

    我在计划任务中使用了以下内容,它按预期工作:

    $url="http://server/uri"
    (New-Object System.Net.WebClient).DownloadString("$url");
    
  • 1

    您需要将该日志文件放在共享目录中的某个位置 . 计划任务可能有也可能无法访问 $env:USERPROFILE . 此外,使用 Start-Transcript 让PowerShell将脚本的输出写入日志文件( STDOUT 除外,您需要将可执行文件的输出通过管道传输到Write-Host,例如 hostname | Write-Host ) .

    $url = "http://example.com"
    
    $log_file = "C:\PlanificationLogs\Planification.log"
    Start-Transcript -Path $log_file
    
    Get-Date -UFormat "%d/%m/%Y %R"
    Write-Host "$date [INFO] Exécution de $url" 
    
    # PowerShell 3
    Invoke-WebRequest -Uri $url
    
    # PowerShell 2
    $request = [System.Net.WebRequest]::Create($url)
    $response = $request.GetResponse()
    $response.Close()
    
  • 11

    以下代码应该做你需要的 .

    $url = "http://www.google.com"
    PowerShell Invoke-WebRequest -Uri $url -Method GET
    

相关问题