当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 下载 SysInternals

作者:精品下载站 日期:2024-12-14 07:40:18 浏览:16 分类:玩电脑

使用 PowerShell 下载 SysInternals


[玩转系统] 使用 PowerShell 下载 SysInternals

#requires -version 3.0

<#
Download Sysinternals tools from web to a local folder.

  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************
#>

[cmdletbinding(SupportsShouldProcess)]

Param(
[Parameter(Position=0)]
[ValidateScript({Test-Path -Path $_})]
[string]$Destination = "G:\SysInternals"
)

#start the WebClient service if it is not running
if ((Get-Service WebClient).Status -eq 'Stopped') {
     Write-Verbose "Starting WebClient"
     #always start the webclient service even if using -Whatif
     Start-Service WebClient -WhatIf:$false
     $Stopped = $True
}
else {
    <#
     Define a variable to indicate service was already running
     so that we don't stop it. Making an assumption that the
     service is already running for a reason.
    #>
    $Stopped = $False
}

#get current files in destination
$current = dir -Path $Destination -File

Write-Host "Updating Sysinternals tools from \live.sysinternals.com\tools to $destination" -ForegroundColor Cyan

foreach ($file in $current) {
  #construct a path to the live web version and compare dates
  $online = Join-Path -path \live.sysinternals.com\tools -ChildPath $file.name
  Write-Verbose "Testing $online"
  if ((Get-Item -Path $online).LastWriteTime.Date -ge $file.LastWriteTime.Date) {
    Copy-Item $online -Destination $Destination -PassThru
  }
}

Write-Host "Testing for online files not in $destination" -ForegroundColor Green

#test for files online but not in the destination and copy them
dir -path \live.sysinternals.com\tools -file | 
Where {$current.name -notcontains $_.name} |
Copy-Item -Destination $Destination -PassThru

<#
alternative but this might still copy files that haven't
really changed
Robocopy \live.sysinternals.com\tools $destination /MIR
#>

if ( $Stopped ) {
    Write-Verbose "Stopping web client"
    #always stop the service even if using -Whatif
    Stop-Service WebClient -WhatIf:$False
}

Write-Host "Sysinternals Update Complete" -ForegroundColor Cyan
#end of script

我的版本需要 PowerShell 3.0。您需要运行 WebClient 服务才能列出 Internet 文件。我的脚本包含根据需要启动和停止服务的代码。尽管如果它检测到服务已经在运行,脚本也不会停止它(假设您可能出于某种原因运行它)。

脚本背后的逻辑非常简单,如果在线版本的日期大于本地版本,则复制文件。我遇到的一件事是,由于时区和/或夏令时,时间戳可能会存在差异。我找不到一种简单的方法来考虑这些事情,所以我选择简单地测试日期并忽略时间。

我应该做的下一件事是设置一个 PowerShell 计划作业以每月运行该脚本。我希望您能让我知道这对您来说效果如何。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯