通过一个简单的 PowerShell 脚本加 Windows 计划任务,完成了这项工作。
相关步骤如下:
1.解除系统对PowerShell脚本执行的禁止
由于默认系统中PowerShell脚本没有足够的权限运行,因此我们需要手动修改并赋予其执行权限,步骤如下:
控制面板 - 管理工具 - Windows PowerShell Modules
PS C:\Windows\system32> Get-ExecutionPolicy
Restricted
PS C:\Windows\system32> Set-ExecutionPolicy RemoteSigned
执行策略更改
执行策略可以防止您执行不信任的脚本。更改执行策略可能会使您面临 about_Execution_Policies
帮助主题中所述的安全风险。是否要更改执行策略?
[Y] 是(Y) [N] 否(N) [S] 挂起(S) [?] 帮助 (默认值为“Y”): Y
至此,便解除了系统对PowerShell脚本执行的禁止。
2.编写PowerShell脚本
新建一个文本文件,命名为 del-expired.ps1内容如下:
echo "These expired files have been deleted:"
$a = Get-ChildItem D:\Danny\TestForDelExpiredFile
# Replace the directory here to in which you want to delete files
foreach ($x in $a)
{
$y = ((Get-Date) - $x.LastWriteTime).Days
# Replace the 1 here, 1 means the file have existed for more than 1 days
# [$x.PsISContainer -ne $True] Judge whether x is directory or not!
if ($y -gt 1 -and $x.PsISContainer -ne $True)
{
$x.Delete()
#echo $x
[System.Console]::WriteLine("File " + $x + " has been deleted!");
}
}
因为我们发现Windows的计划任务不能直接调用PowerShell脚本来执行。所以,我们需要再新建一个文本文件,命名为del-expired.bat
内容如下:
powershell D:\Danny\del-expired.ps1
#替换这里的 D:\Danny\del-expired.ps1 为你的脚本实际存放位置
3.使用Windows计划任务来定期执行脚本
控制面板-管理工具-任务计划程序-创建任务
配置如下:
常规:输入 名称,描述 - 勾选“不管用户是否登录都要运行” -输入密码 - 勾选“使用最高权限运行”
触发器:新建 - 选择“制定计划时” - 选择 执行时间如“7:30:00” - 选择执行周期如“每天 每隔1天发生一次” - 勾选“启用”
操作:新建 - 选择“启动程序” - “浏览”刚刚创建好的del-expired.bat脚本 - 点击“确定”
至此,计划任务就配置完成了,如果想要测试计划任务是否能正常执行,直接手动立即运行一次即可。
原文:http://heylinux.com/archives/tag/powershell
收录一个相关参考链接:http://wenku.baidu.com/view/6f084cc408a1284ac85043e7.html