Posts Tagged ‘Scripts’

Windows PowerShell Execution Policies

Wednesday, May 28th, 2008

Windows Powershell sets its Execution Policy to Restricted by default, which states that PowerShell can only be used in interactive mode (no scripts will run.) Use the Get-ExecutionPolicy cmdlet to check which execution policy is currently in-force.

$ Get-ExecutionPolicy

The following execution policy definitions are from Microsoft’s website:

  • Restricted – No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned – Only scripts signed by a trusted publisher can be run.
  • RemoteSigned – Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted – No restrictions; all Windows PowerShell scripts can be run.

To change the execution policy, use Set-ExecutionPolicy. The following will enable you to execute all PowerShell scripts.

$ Set-ExecutionPolicy Unrestricted

Windows PowerShell – Recursively delete files and directories modified more than ‘n’ days ago.

Thursday, May 22nd, 2008

I was recently tasked with writing a script that recursively deletes files and directories modified more than ‘n’ days ago – here’s the kicker – using Windows. Many people have accomplished this with long VB Scripts. I was hoping for a much cleaner solution, and decided to try Windows PowerShell . I am quite impressed with Windows Powershell’s capabilities.

The following script recursively deletes files and directories modified more than 16 days ago.

# prune.ps1
$sticky = (Get-date).AddDays(-16)
$backupDir = "B:\backup"
echo "Recursively deleting files and directories written before $sticky"
Get-ChildItem $backupDir -Recurse | Where-Object { $_.LastWriteTime -lt $sticky } | Remove-Item -Recurse

Note that you can change Remove-Item -Recurse to Remove-Item -Whatif to “pretend” to delete files, and display potential deletes on STDOUT. You can also specify Remove-Item -Confirm.

I created a scheduled task that runs a .bat file containing the following:
powershell.exe c:\scripts\prune.ps1 >> c:\scripts\logs\prune.log

To watch and or view the output of the script, specify the -noexit switch on the command line.
powershell.exe -noexit c:\scripts\prune.ps1