Help modifying a powershell script

Hello,
I have recently been given a task to write/find a script that is capable of performing Full and Incremental backups. I found a script that does exactly what I need, however, it requires user input. I need this to be a scheduled task and therefore I need
the input to be a static path. Here is the script I am talking about:
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$HashPath,
[Parameter(Position=3, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateSet("Full","Incremental","Differential")] 
[System.String]
$BackupType="Full",
[Parameter(Position=4, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]  
[System.String]
$LogFile=".\Backup-Files.log",
[Parameter(Position=5, Mandatory=$false,ValueFromPipeline=$false)]
[System.Management.Automation.SwitchParameter]
$SwitchToFull
#endregion 
begin{
function Write-Log
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Message,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile
#endregion
try{
Write-Host $Message
Out-File -InputObject $Message -Append $LogFile
catch {throw $_}
function Get-Hash 
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashTarget,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateSet("File","String")]
[System.String]
$HashType
#endregion
begin{
try{ $objGetHashMD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider } 
catch {throw $_ }
process{
try {
#Checking hash target is file or just string
switch($HashType){
"String" {
$objGetHashUtf8 = New-Object -TypeName System.Text.UTF8Encoding
$arrayGetHashHash = $objGetHashMD5.ComputeHash($objGetHashUtf8.GetBytes($HashTarget.ToUpper()))
break
"File" {
$arrayGetHashHash = $objGetHashMD5.ComputeHash([System.IO.File]::ReadAllBytes($HashTarget))
break
#Return hash
Write-Output $([System.Convert]::ToBase64String($arrayGetHashHash))
catch { throw $_ }
function Copy-File
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Any'})] 
[System.String]
$SourceFile,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()] 
[System.String]
$DestFile
#endregion
try{
#The script fails when folder being copied to file. So the item will be removed to avoid the error.
if(Test-Path -LiteralPath $DestFile -PathType Any){
Remove-Item -LiteralPath $DestFile -Force -Recurse
#Creating destination if doesn't exist. It's required because Copy-Item doesn't create destination folder
if(Test-Path -LiteralPath $SourceFile -PathType Leaf){
New-Item -ItemType "File" -Path $DestFile -Force
#Copying file to destination directory
Copy-Item -LiteralPath $SourceFile -Destination $DestFile -Force
catch{ throw $_ }
function Backup-Files
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()] 
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNull()] 
[System.Collections.Hashtable]
$HashTable
#endregion
try{
$xmlBackupFilesHashFile = $HashTable
Write-Host "Backup started" 
Get-ChildItem -Recurse -Path $SourceDir|ForEach-Object{
$currentBackupFilesItem = $_
#Full path to source and destination item
$strBackupFilesSourceFullPath = $currentBackupFilesItem.FullName
$strBackupFilesDestFullPath = $currentBackupFilesItem.FullName.Replace($SourceDir,$DestDir)
#Checking that the current item is file and not directory. True - the item is file. 
$bBackupFilesFile = $($($currentBackupFilesItem.Attributes -band [System.IO.FileAttributes]::Directory) -ne [System.IO.FileAttributes]::Directory)
Write-Host -NoNewline ">>>Processing item $strBackupFilesSourceFullPath..."
#Generating path hash
$hashBackupFilesPath = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "String")
$hashBackupFilesFile = "d"
#If the item is file then generate hash for file content
if($bBackupFilesFile){
$hashBackupFilesFile = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "File")
#Checking that the file has been copied
if($xmlBackupFilesHashFile[$hashBackupFilesPath] -ne $hashBackupFilesFile){
Write-Host -NoNewline $("hash changed=>$hashBackupFilesFile...")
Copy-File -SourceFile $strBackupFilesSourceFullPath $strBackupFilesDestFullPath|Out-Null
#Returning result
Write-Output @{$hashBackupFilesPath=$hashBackupFilesFile}
else{
Write-Host -NoNewline "not changed..."
Write-Host "done"
Write-Host "Backup completed"
catch { throw $_ }
function Backup-Full
[CmdletBinding()]
[OutputType([System.String])]
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()] 
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()] 
[System.String]
$HashFile,
[Parameter(Position=3, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]  
[System.String]
$ChainKey
#endregion
try{
#Creating an empty hash table
$xmlBackupFullHashFile = @{}
#Starting directory lookup 
$uintBackupFullCount = 0
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$ChainKey\Full_" + $(Get-Date -Format "ddMMyyyy")) -HashTable $xmlBackupFullHashFile|`
ForEach-Object{ 
$xmlBackupFullHashFile.Add([string]$_.Keys,[string]$_.Values) 
$uintBackupFullCount++
#Saving chain key.
$xmlBackupFullHashFile.Add("ChainKey",$ChainKey)
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupFullHashFile -Force
Write-Host "done"
Write-Output $uintBackupFullCount
catch { throw $_ }
function Backup-Diff
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()] 
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupDiffHashFile = Import-Clixml $HashFile
$chainKeyBackupDiffDifferential = $xmlBackupDiffHashFile["ChainKey"]
$uintBackupDiffCount = 0
#Starting directory lookup 
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupDiffDifferential\Differential_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupDiffHashFile|`
ForEach-Object{ $uintBackupDiffCount++ }
Write-Output $uintBackupDiffCount
catch { throw $_ }
function Backup-Inc
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})] 
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()] 
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupIncHashFile = Import-Clixml $HashFile
$chainKeyBackupIncIncremental = $xmlBackupIncHashFile["ChainKey"]
$uintBackupIncCount = 0
#Starting directory lookup 
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupIncIncremental\Incremental_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupIncHashFile|`
ForEach-Object{ 
$xmlBackupIncHashFile[[string]$_.Keys]=[string]$_.Values
$uintBackupIncCount++
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupIncHashFile -Force
Write-Host "Done"
Write-Output $uintBackupIncCount
catch { throw $_ }
#0 - is OK. 1 - some error
$exitValue=0
process{
try{
$filesCopied=0
$strSourceFolderName = $(Get-Item $SourceDir).Name
$strHasFile = $("$HashPath\Hash_$strSourceFolderName.xml")
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir started")
#Automatically switch to full backup
$bSwitch = $(!$(Test-Path -LiteralPath $strHasFile -PathType "Leaf") -and $SwitchToFull)
Write-Log -Message $strMessage -LogFile $LogFile
switch($true){
$($BackupType -eq "Full" -or $bSwitch) {
$filesCopied = Backup-Full -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile -ChainKey $("Backup_$strSourceFolderName" + "_" + $(Get-Date -Format "ddMMyyyy"))
break
$($BackupType -eq "Incremental") {
$filesCopied = Backup-Inc -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile 
break
$($BackupType -eq "Differential") {
$filesCopied = Backup-Diff -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile 
break
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir completed successfully. $filesCopied items were copied.")
Write-Log -Message $strMessage -LogFile $LogFile
Write-Output $filesCopied
catch { 
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir failed:" + $_)
Write-Log -Message $strMessage -LogFile $LogFile
$exitValue = 1
end{exit $exitValue}
I have some experience writing Powershell scripts,but I am lost at how this script prompts for Source and Destination paths. I tried modifying the Param section, but this didnt work and up until now I thought the only way you could get a prompt was with
"read-host". Any and all education on this matter would be greatly appreciated. (Side note: I have posted this question  on the forum in which I found it and have not got an answer yet).
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$HashPath,
[Parameter(Position=3, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateSet("Full","Incremental","Differential")]
[System.String]
$BackupType="Full",
[Parameter(Position=4, Mandatory=$false,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile=".\Backup-Files.log",
[Parameter(Position=5, Mandatory=$false,ValueFromPipeline=$false)]
[System.Management.Automation.SwitchParameter]
$SwitchToFull
#endregion
begin{
function Write-Log
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Message,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LogFile
#endregion
try{
Write-Host $Message
Out-File -InputObject $Message -Append $LogFile
catch {throw $_}
function Get-Hash
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashTarget,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateSet("File","String")]
[System.String]
$HashType
#endregion
begin{
try{ $objGetHashMD5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
catch {throw $_ }
process{
try {
#Checking hash target is file or just string
switch($HashType){
"String" {
$objGetHashUtf8 = New-Object -TypeName System.Text.UTF8Encoding
$arrayGetHashHash = $objGetHashMD5.ComputeHash($objGetHashUtf8.GetBytes($HashTarget.ToUpper()))
break
"File" {
$arrayGetHashHash = $objGetHashMD5.ComputeHash([System.IO.File]::ReadAllBytes($HashTarget))
break
#Return hash
Write-Output $([System.Convert]::ToBase64String($arrayGetHashHash))
catch { throw $_ }
function Copy-File
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Any'})]
[System.String]
$SourceFile,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestFile
#endregion
try{
#The script fails when folder being copied to file. So the item will be removed to avoid the error.
if(Test-Path -LiteralPath $DestFile -PathType Any){
Remove-Item -LiteralPath $DestFile -Force -Recurse
#Creating destination if doesn't exist. It's required because Copy-Item doesn't create destination folder
if(Test-Path -LiteralPath $SourceFile -PathType Leaf){
New-Item -ItemType "File" -Path $DestFile -Force
#Copying file to destination directory
Copy-Item -LiteralPath $SourceFile -Destination $DestFile -Force
catch{ throw $_ }
function Backup-Files
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNull()]
[System.Collections.Hashtable]
$HashTable
#endregion
try{
$xmlBackupFilesHashFile = $HashTable
Write-Host "Backup started"
Get-ChildItem -Recurse -Path $SourceDir|ForEach-Object{
$currentBackupFilesItem = $_
#Full path to source and destination item
$strBackupFilesSourceFullPath = $currentBackupFilesItem.FullName
$strBackupFilesDestFullPath = $currentBackupFilesItem.FullName.Replace($SourceDir,$DestDir)
#Checking that the current item is file and not directory. True - the item is file.
$bBackupFilesFile = $($($currentBackupFilesItem.Attributes -band [System.IO.FileAttributes]::Directory) -ne [System.IO.FileAttributes]::Directory)
Write-Host -NoNewline ">>>Processing item $strBackupFilesSourceFullPath..."
#Generating path hash
$hashBackupFilesPath = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "String")
$hashBackupFilesFile = "d"
#If the item is file then generate hash for file content
if($bBackupFilesFile){
$hashBackupFilesFile = $(Get-Hash -HashTarget $strBackupFilesSourceFullPath -HashType "File")
#Checking that the file has been copied
if($xmlBackupFilesHashFile[$hashBackupFilesPath] -ne $hashBackupFilesFile){
Write-Host -NoNewline $("hash changed=>$hashBackupFilesFile...")
Copy-File -SourceFile $strBackupFilesSourceFullPath $strBackupFilesDestFullPath|Out-Null
#Returning result
Write-Output @{$hashBackupFilesPath=$hashBackupFilesFile}
else{
Write-Host -NoNewline "not changed..."
Write-Host "done"
Write-Host "Backup completed"
catch { throw $_ }
function Backup-Full
[CmdletBinding()]
[OutputType([System.String])]
#region Params
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$HashFile,
[Parameter(Position=3, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$ChainKey
#endregion
try{
#Creating an empty hash table
$xmlBackupFullHashFile = @{}
#Starting directory lookup
$uintBackupFullCount = 0
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$ChainKey\Full_" + $(Get-Date -Format "ddMMyyyy")) -HashTable $xmlBackupFullHashFile|`
ForEach-Object{
$xmlBackupFullHashFile.Add([string]$_.Keys,[string]$_.Values)
$uintBackupFullCount++
#Saving chain key.
$xmlBackupFullHashFile.Add("ChainKey",$ChainKey)
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupFullHashFile -Force
Write-Host "done"
Write-Output $uintBackupFullCount
catch { throw $_ }
function Backup-Diff
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupDiffHashFile = Import-Clixml $HashFile
$chainKeyBackupDiffDifferential = $xmlBackupDiffHashFile["ChainKey"]
$uintBackupDiffCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupDiffDifferential\Differential_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupDiffHashFile|`
ForEach-Object{ $uintBackupDiffCount++ }
Write-Output $uintBackupDiffCount
catch { throw $_ }
function Backup-Inc
#region Params
[CmdletBinding()]
[OutputType([System.String])]
param(
[Parameter(Position=0, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'Container'})]
[System.String]
$SourceDir,
[Parameter(Position=1, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestDir,
[Parameter(Position=2, Mandatory=$true,ValueFromPipeline=$false)]
[ValidateScript({Test-Path -LiteralPath $_ -PathType 'leaf'})]
[System.String]
$HashFile
#endregion
try{
#Loading hash table
$xmlBackupIncHashFile = Import-Clixml $HashFile
$chainKeyBackupIncIncremental = $xmlBackupIncHashFile["ChainKey"]
$uintBackupIncCount = 0
#Starting directory lookup
Backup-Files -SourceDir $SourceDir -DestDir $("$DestDir\$chainKeyBackupIncIncremental\Incremental_" + $(Get-Date -Format "ddMMyyyy.HHmm")) -HashTable $xmlBackupIncHashFile|`
ForEach-Object{
$xmlBackupIncHashFile[[string]$_.Keys]=[string]$_.Values
$uintBackupIncCount++
Write-Host -NoNewline "Saving XML file to $HashFile..."
Export-Clixml -Path $HashFile -InputObject $xmlBackupIncHashFile -Force
Write-Host "Done"
Write-Output $uintBackupIncCount
catch { throw $_ }
#0 - is OK. 1 - some error
$exitValue=0
process{
try{
$filesCopied=0
$strSourceFolderName = $(Get-Item $SourceDir).Name
$strHasFile = $("$HashPath\Hash_$strSourceFolderName.xml")
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir started")
#Automatically switch to full backup
$bSwitch = $(!$(Test-Path -LiteralPath $strHasFile -PathType "Leaf") -and $SwitchToFull)
Write-Log -Message $strMessage -LogFile $LogFile
switch($true){
$($BackupType -eq "Full" -or $bSwitch) {
$filesCopied = Backup-Full -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile -ChainKey $("Backup_$strSourceFolderName" + "_" + $(Get-Date -Format "ddMMyyyy"))
break
$($BackupType -eq "Incremental") {
$filesCopied = Backup-Inc -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$($BackupType -eq "Differential") {
$filesCopied = Backup-Diff -SourceDir $SourceDir -DestDir $DestDir -HashFile $strHasFile
break
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir completed successfully. $filesCopied items were copied.")
Write-Log -Message $strMessage -LogFile $LogFile
Write-Output $filesCopied
catch {
$strMessage = $($(Get-Date -Format "HH:mm_dd.MM.yyyy;") + "$BackupType backup of $SourceDir failed:" + $_)
Write-Log -Message $strMessage -LogFile $LogFile
$exitValue = 1
end{exit $exitValue}

Hi Ryan Blaeholder,
Thanks for your posting.
To schedule a powershell script with input value, instead of modifying the script above, you can also try to add the input during creating a scheduled task like this:(save the script above as D:\backup.ps1)
-command "& 'D:\backup.ps1' 'input1' 'input2'"
For more detailed information, please refer to this article to complete:
Schedule PowerShell Scripts that Require Input Values:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/schedule-powershell-scripts-that-require-input-values.aspx
I hope this helps.
We
are trying to better understand customer views on social support experience, so your participation in this
interview project would be greatly appreciated if you have time.
Thanks for helping make community forums a great place.

Similar Messages

  • Please help me with Powershell Script - Message Box to display after Installation

    Hi Guys,
    Am using package model to deploy the software. After installation on client machines i want to display a dialog box to notify the successful installation.
    Currently trying VBScript to show the dialog message.
    But few machines i get this dialog and few machines am not getting, in program command line am calling a batch script.
    Now am planning to use a Power shell scripting to show a message box and trying to call it through a batch script.
    Please assist me with the powershell script which will display a message box like above
    (and let me know in script how to enable the set-execution policy Remote signed enabled)
    Thanks,

    You can set the execution settings from within the client settings.
    For a simple message box without having to load assmemblies
    $wshell = New-Object -ComObject Wscript.Shell
    $wshell.Popup("Operation Completed",0,"Done",0x1)

  • [SOLVED] (Perl) Help Modifying Conky Weather Script

    I'm using buttons' excellent Conky weather script, but it has more information than I need. It displays both the current weather condition and the temperature:
    [condition]:[temperature]F
    so right now it's
    Clear: 46F
    All I need is for it to display the temperature, without the current condition, colon, and letter 'F' (for Fahrenheit).
    the script:
    METRIC=0 #Should be 0 or 1; 0 for F, 1 for C
    if [ -z $1 ]; then
    echo
    echo "USAGE: weather.sh <locationcode>"
    echo
    exit 0;
    fi
    curl -s http://rss.accuweather.com/rss/liveweather_rss.asp\?metric\=${METRIC}\&locCode\=$1 | perl -ne 'if (/Currently/) {chomp;/\<title\>Currently: (.*)?\<\/title\>/; print "$1"; }'
    In Conky:
    {execi 300 /home/hex/.conky/weather.sh <zip code>}
    I'm not familiar with Perl yet so any help is much appreciated
    Last edited by Olson (2011-02-17 07:06:10)

    Try this
    curl ... | perl -ne 'if (/Currently/) {chomp;/\<title\>.*: (\d*).\<\/title\>/; print "$1"; }'

  • Can anyone help with a powershell script using the search-adaccount cmdlet to filter out accounts that have been created in the last 90 days?

    Hi,
    I have the following script that is supposed to search AD for all user accounts that haven't logged into the domain in more than 90 days.  I first did not have the where-object clause because I didn't realize the search-adaccount would provide results
    back of users that have never logged in, but were created less than 90 days ago.  So I tried to incorporate the logic to not include user accounts that were created in the last 90 days.
    #requires -version 4
    #This script creates a file of accounts that have not been logged into in the past 90 days, excluding accounts that have been created within the past 90 days since the -AccountInactive option does not factor for the whenCreated property of an AD object
    $DateThreshold = ((Get-Date).AddDays(-90))
    $ReportDate = Get-Date -Format yyyy-MM-dd
    #Create a folder according to the current date to be used for storing the report
    New-Item -Path ".\$ReportDate" -ItemType Directory
    $InactiveUsers = Search-ADAccount -UsersOnly -AccountInactive -TimeSpan "90" -SearchBase "OU=XXXX,DC=XXXX,DC=XXXX,DC=XXXX" | Where-Object {$_.whenCreated -gt $DateThreshold} | Export-Csv ".\$ReportDate\Inactive90_$ReportDate.csv"
    However, I can't ever get the whenCreated field to populate with data.  What gives?

    Hi,
    Search-ADAccount doesn't return a whenCreated property. If you want that, you'll need to use Get-ADUser as well. Here's a basic example you can build from:
    $dateThreshold = (Get-Date).AddDays(-90)
    Search-ADAccount -UsersOnly -SearchBase 'OU=Users,DC=domain,DC=com' -AccountDisabled | ForEach {
    $whenCreated = (Get-ADUser -Identity $_.SamAccountName -Properties whenCreated).whenCreated
    If ($whenCreated -gt $dateThreshold) {
    $_
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • Help sought getting powershell script to run

    Platform is SP 2010 service pack 2.
    Goal is to generate a list of users within the farm that are no longer in active directory.
    http://sharepointpsscripts.codeplex.com/releases/view/21699  is a script that purports to accomplish this.
    However, what I am seeing is a script that has executed for more than 12 hours, with the only output being sent to the console and consisting of logins and the error:
    FindAll : Exception calling "FindAll" with "0" argument(s): "A referral was returned from
    the server.
    At C:\Users\sa_spfarm\desktop\check-sporphans.ps1:20 char:36
    +     $colResults = $objSearcher.FindAll <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException
    I am logged into a farm server as the farm admin account. 
    The bit of code that is failing is:
    function Check_User_In_ActiveDirectory([string]$LoginName, [string]$domaincnx)
    $returnValue = $false
    #Filter on User which exists and activated
    #$strFilter = "(&(objectCategory=user)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(samAccountName=$LoginName))"
    #Filter on User which only exists
    #$strFilter = "(&(objectCategory=user)(objectClass=user)(samAccountName=$LoginName))"
    #Filter on User and NTgroups which only exists
    $strFilter = "(&(|(objectCategory=user)(objectCategory=group))(samAccountName=$LoginName))"
    $objDomain = New-Object System.DirectoryServices.DirectoryEntry($domaincnx)
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.SearchRoot = $objDomain
    $objSearcher.PageSize = 1000
    $objSearcher.Filter = $strFilter
    $objSearcher.SearchScope = "Subtree"
    #$objSearcher.PropertiesToLoad.Add("name")
    $colResults = $objSearcher.FindAll()
    if($colResults.Count -gt 0)
    #Write-Host "Account exists and Active: ", $LoginName
    $returnValue = $true
    return $returnValue
    This function is called by another which is called by another. The code came from the URL above.
    What output is occurring other than the error is a string of write-host cmdlets that are listing some logins that used to exist on the farm. 
    I am thinking that iif there is no error trapping - and I don't see anything obviously trapping errors - and the login is no longer in active directory (the whole purpose of the script) then the attempt to perform the findall would fail, and perhaps raise
    the above error?
    What happens to the program flow at that point?
    Does findall return a 0?  That seems to be what the code is expecting?  But if that were the case, then when this function returns, the function which calls it looks at the 0 return code and compares it to $False. If the return code is equal to
    $False, then the write-output occurs.
    I am trying to figure out how to tweak the script so that I actually get results output.
    Thanks for any ideas you might be able to suggest.

    What's the format of the domain that you're using in the script?
    This post is my own opinion and does not necessarily reflect the opinion or view of Slalom.

  • Need Help on powershell Script to send mails in different languages

    Hello, Just wanted to use the script below to remind users of password expiry date (I got it from internet New-Passwordreminder.ps1). We have companies in many countries, so the email should be in the language of that country. So since our users are in different
    OU's according to countries, I thought some one could help me edit this script and say if the user is in AB ou then email in english will be sent, if in BC ou then the email will be in Russian....So in the script I will have all the languages I need
    to have written.
    <#
    .SYNOPSIS
      Notifies users that their password is about to expire.
    .DESCRIPTION
        Let's users know their password will soon expire. Details the steps needed to change their password, and advises on what the password policy requires. Accounts for both standard Default Domain Policy based password policy and the fine grain
    password policy available in 2008 domains.
    .NOTES
        Version            : v2.6 - See changelog at
    http://www.ehloworld.com/596
        Wish list      : Better detection of Exchange server
                  : Set $DaysToWarn automatically based on Default Domain GPO setting
                  : Description for scheduled task
                  : Verify it's running on R2, as apparently only R2 has the AD commands?
                  : Determine password policy settings for FGPP users
                  : better logging
        Rights Required   : local admin on server it's running on
        Sched Task Req'd  : Yes - install mode will automatically create scheduled task
        Lync Version    : N/A
        Exchange Version  : 2007 or later
        Author           : M. Ali (original AD query), Pat Richard, Exchange MVP
        Email/Blog/Twitter :
    [email protected]  http://www.ehloworld.com @patrichard
        Dedicated Post   :
    http://www.ehloworld.com/318
        Disclaimer       : You running this script means you won't blame me if this breaks your stuff.
        Info Stolen from   : (original)
    http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
                  : (date)
    http://technet.microsoft.com/en-us/library/ff730960.aspx
                : (calculating time)
    http://blogs.msdn.com/b/powershell/archive/2007/02/24/time-till-we-land.aspx
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/23fc5ffb-7cff-4c09-bf3e-2f94e2061f29/
    http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
                : (password decryption)
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/f90bed75-475e-4f5f-94eb-60197efda6c6/
                : (determine per user fine grained password settings)
    http://technet.microsoft.com/en-us/library/ee617255.aspx
    .LINK    
        http://www.ehloworld.com/318
    .INPUTS
      None. You cannot pipe objects to this script
    .PARAMETER Demo
      Runs the script in demo mode. No emails are sent to the user(s), and onscreen output includes those who are expiring soon.
    .PARAMETER Preview
      Sends a sample email to the user specified. Usefull for testing how the reminder email looks.
    .PARAMETER PreviewUser
      User name of user to send the preview email message to.
    .PARAMETER Install
      Create the scheduled task to run the script daily. It does NOT create the required Exchange receive connector.
    .EXAMPLE
      .\New-PasswordReminder.ps1
      Description
      Searches Active Directory for users who have passwords expiring soon, and emails them a reminder with instructions on how to change their password.
    .EXAMPLE
      .\New-PasswordReminder.ps1 -demo
      Description
      Searches Active Directory for users who have passwords expiring soon, and lists those users on the screen, along with days till expiration and policy setting
    .EXAMPLE
      .\New-PasswordReminder.ps1 -Preview -PreviewUser [username]
      Description
      Sends the HTML formatted email of the user specified via -PreviewUser. This is used to see what the HTML email will look like to the users.
    .EXAMPLE
      .\New-PasswordReminder.ps1 -install
      Description
      Creates the scheduled task for the script to run everyday at 6am. It will prompt for the password for the currently logged on user. It does NOT create the required Exchange receive connector.
    #>
    #Requires -Version 2.0
    [cmdletBinding(SupportsShouldProcess = $true)]
    param(
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Demo,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Preview,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Install,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [string]$PreviewUser
    Write-Verbose "Setting variables"
    [string]$Company = "Contoso Ltd"
    [string]$OwaUrl = "https://mail.contoso.com"
    [string]$PSEmailServer = "10.9.0.11"
    [string]$EmailFrom = "Help Desk <[email protected]>"
    [string]$HelpDeskPhone = "(586) 555-1010"
    [string]$HelpDeskURL = "https://intranet.contoso.com/"
    [string]$TranscriptFilename = $MyInvocation.MyCommand.Name + " " + $env:ComputerName + " {0:yyyy-MM-dd hh-mmtt}.log" -f (Get-Date)
    [int]$global:UsersNotified = 0
    [int]$DaysToWarn = 14
    [string]$ImagePath = "http://www.contoso.com/images/new-passwordreminder.ps1"
    [string]$ScriptName = $MyInvocation.MyCommand.Name
    [string]$ScriptPathAndName = $MyInvocation.MyCommand.Definition
    [string]$ou
    [string]$DateFormat = "d"
    if ($PreviewUser){
     $Preview = $true
    Write-Verbose "Defining functions"
    function Set-ModuleStatus {
     [cmdletBinding(SupportsShouldProcess = $true)]
     param (
      [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, HelpMessage = "No module name specified!")]
      [string]$name
     if(!(Get-Module -name "$name")) {
      if(Get-Module -ListAvailable | ? {$_.name -eq "$name"}) {
       Import-Module -Name "$name"
       # module was imported
       return $true
      } else {
       # module was not available (Windows feature isn't installed)
       return $false
     }else {
      # module was already imported
      return $true
    } # end function Set-ModuleStatus
    function Remove-ScriptVariables { 
     [cmdletBinding(SupportsShouldProcess = $true)]
     param($path)
     $result = Get-Content $path | 
     ForEach { if ( $_ -match '(\$.*?)\s*=') {     
       $matches[1]  | ? { $_ -notlike '*.*' -and $_ -notmatch 'result' -and $_ -notmatch 'env:'} 
     ForEach ($v in ($result | Sort-Object | Get-Unique)){  
      Remove-Variable ($v.replace("$","")) -ErrorAction SilentlyContinue
    } # end function Get-ScriptVariables
    function Install {
     [cmdletBinding(SupportsShouldProcess = $true)]
     param()
    http://technet.microsoft.com/en-us/library/cc725744(WS.10).aspx
     $error.clear()
     Write-Host "Creating scheduled task `"$ScriptName`"..."
     $TaskPassword = Read-Host "Please enter the password for $env:UserDomain\$env:UserName" -AsSecureString
     $TaskPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($TaskPassword))
     # need to fix the issue with spaces in the path
     schtasks /create /tn $ScriptName /tr "$env:windir\system32\windowspowershell\v1.0\powershell.exe -psconsolefile '$env:ExchangeInstallPath\Bin\exshell.psc1' -command $ScriptPathAndName" /sc Daily /st 06:00 /ru $env:UserDomain\$env:UserName /rp
    $TaskPassword | Out-Null
     if (!($error)){
      Write-Host "done!" -ForegroundColor green
     }else{
      Write-Host "failed!" -ForegroundColor red
     exit
    } # end function Install
    function Get-ADUserPasswordExpirationDate {
     [cmdletBinding(SupportsShouldProcess = $true)]
     Param (
      [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, HelpMessage = "Identity of the Account")]
      [Object]$accountIdentity
     PROCESS {
      Write-Verbose "Getting the user info for $accountIdentity"
      $accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet, name, mail
      # Make sure the password is not expired, and the account is not set to never expire
        Write-Verbose "verifying that the password is not expired, and the user is not set to PasswordNeverExpires"
        if (((!($accountObj.PasswordExpired)) -and (!($accountObj.PasswordNeverExpires))) -or ($PreviewUser)) {
         Write-Verbose "Verifying if the date the password was last set is available"
         $passwordSetDate = $accountObj.PasswordLastSet      
          if ($passwordSetDate -ne $null) {
           $maxPasswordAgeTimeSpan = $null
            # see if we're at Windows2008 domain functional level, which supports granular password policies
            Write-Verbose "Determining domain functional level"
            if ($global:dfl -ge 4) { # 2008 Domain functional level
              $accountFGPP = Get-ADUserResultantPasswordPolicy $accountObj
              if ($accountFGPP -ne $null) {
               $maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
         } else {
          $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
        } else { # 2003 or ealier Domain Functional Level
         $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
        if ($maxPasswordAgeTimeSpan -eq $null -or $maxPasswordAgeTimeSpan.TotalMilliseconds -ne 0) {
         $DaysTillExpire = [math]::round(((New-TimeSpan -Start (Get-Date) -End ($passwordSetDate + $maxPasswordAgeTimeSpan)).TotalDays),0)
         if ($preview){$DaysTillExpire = 1}
         if ($DaysTillExpire -le $DaysToWarn){
          Write-Verbose "User should receive email"
          $PolicyDays = [math]::round((($maxPasswordAgeTimeSpan).TotalDays),0)
          if ($demo) {Write-Host ("{0,-25}{1,-8}{2,-12}" -f $accountObj.Name, $DaysTillExpire, $PolicyDays)}
                # start assembling email to user here
          $EmailName = $accountObj.Name      
          $DateofExpiration = (Get-Date).AddDays($DaysTillExpire)
          $DateofExpiration = (Get-Date($DateofExpiration) -f $DateFormat)      
    Write-Verbose "Assembling email message"      
    [string]$emailbody = @"
    <html>
     <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     </head>
    <body>
     <table id="email" border="0" cellspacing="0" cellpadding="0" width="655" align="center">
      <tr>
       <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="28" align="absMiddle">
    if ($HelpDeskURL){     
    $emailbody += @" 
       <font style="font-size: 10px; color: #000000; line-height: 16px; font-family: Verdana, Arial, Helvetica, sans-serif">If this e-mail does not appear properly, please <a href="$HelpDeskURL" style="font-weight:
    bold; font-size: 10px; color: #cc0000; font-family: verdana, arial, helvetica, sans-serif; text-decoration: underline">click here</a>.</font>
    $emailbody += @"   
       </td>
      </tr>
      <tr>
    if ($HelpDeskURL){  
    $emailbody += @"
       <td height="121" align="left" valign="bottom"><a href="$HelpDeskURL"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif"
    width="655" height="121"></a></td>
    }else{
    $emailbody += @" 
       <td height="121" align="left" valign="bottom"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif" width="655" height="121"></td>
    $emailbody += @"
      </tr>
      <tr>
       <td>
        <table id="body" border="0" cellspacing="0" cellpadding="0">
         <tr>
          <td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
    height="50"></td>
          <td><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="106"></td>
          <td id="text" width="572" align="left" valign="top" style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif">
    if ($DaysTillExpire -le 1){
     $emailbody += @"
      <div align='center'>
       <table border='0' cellspacing='0' cellpadding='0' style='width:510px; background-color: white; border: 0px;'>
        <tr>
         <td align='right'><img width='36' height='28' src='$ImagePath/image001b.gif' alt='Description: $ImagePath/image001b.gif'></td> 
         <td style="font-family: verdana; background: #E12C10; text-align: center; padding: 0px; font-size: 9.0pt; color: white">ALERT: You must change your password today or you will be locked out!</td>  
         <td align='left'><img border='0' width='14' height='28' src='$ImagePath/image005b.gif' alt='Description: $ImagePath/image005b.gif'></td>
        </tr>
       </table>
      </div>
    $emailbody += @"
       <p style="font-weight: bold">Hello, $EmailName,</p>
       <p>It's change time again! Your $company password expires in <span style="background-color: red; color: white; font-weight: bold;">&nbsp;$DaysTillExpire&nbsp;</span> day(s), on $DateofExpiration.</p>
       <p>Please use one of the methods below to update your password:</p>
       <ol>
        <li>$company office computers and Terminal Server users: You may update your password on your computer by pressing Ctrl-Alt-Delete and selecting 'Change Password' from the available options. If you use a $company laptop in addition
    to a desktop PC, be sure and read #3 below.</li>
        <li>Remote Outlook Client, Mac, and/or Outlook Web App users: If you only access our email system, please use the following method to easily change your password:</li>
        <ul>
         <li>Log into <a href="$owaurl">Outlook Web App</a> using Internet Explorer (PC) or Safari or Firefox (Mac).</li>
         <li>Click on the Options button in the upper right corner of the page.</li>  
         <li>Select the &quot;Change Password&quot; link to change your password.</li>
         <li>Enter your current password, then your new password twice, and click Save</li>
         <li><span style="font-weight: bold">NOTE:</span> You will now need to use your new password when logging into Outlook Web App, Outlook 2010, SharePoint, Windows Mobile (ActiveSync) devices, etc. Blackberry
    Enterprise Users (BES) will not need to update their password. Blackberry Internet Service (BIS) users will be required to use their new password on their device.</li>
        </ul>
        <li>$company issued laptops: If you have been issued a $company laptop, you must be in a corporate office and directly connected to the company network to change your password. If you also use a desktop PC in the office, you must
    remember to always update your domain password on the laptop first. Your desktop will automatically use the new password.</li>
        <ul>
         <li>Log in on laptop</li>
         <li>Press Ctrl-Alt-Delete and select 'Change Password' from the available options.</li>
         <li>Make sure your workstation (if you have one) has been logged off any previous sessions so as to not cause conflict with your new password.</li>
        </ul>
       </ol>
       <p>Think you've got a complex password? Run it through the <a href="The">http://www.passwordmeter.com/">The Password Meter</a></p>
       <p>Think your password couldn't easily be hacked? See how long it would take: <a href="How">http://howsecureismypassword.net/">How Secure Is My Password</a></p>
       <p>Remember, if you do not change your password before it expires on $DateofExpiration, you will be locked out of all $company Computer Systems until an Administrator unlocks your account.</p>
       <p>If you are traveling or will not be able to bring your laptop into the office before your password expires, please call the number below for additional instructions.</p>
       <p>You will continue to receive these emails daily until the password is changed or expires.</p>
       <p>Thank you,<br />
       The $company Help Desk<br />
       $HelpDeskPhone</p>
    if ($accountFGPP -eq $null){
     $emailbody += @"
       <table style="background-color: #dedede; border: 1px solid black">
        <tr>
         <td style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif"><b>$company Password Policy</b>
          <ul>
           <li>Your password must have a minimum of a $MinPasswordLength characters.</li>
           <li>You may not use a previous password.</li>
           <li>Your password must not contain parts of your first, last, or logon name.</li>
           <li>Your password must be changed every $PolicyDays days.</li>
    if ($PasswordComplexity){
     Write-Verbose "Password complexity"
     $emailbody += @"
           <li>Your password requires a minimum of two of the following three categories:</li>
           <ul>
            <li>1 upper case character (A-Z)</li>
            <li>1 lower case character (a-z)</li>
            <li>1 numeric character (0-9)</li>        
           </ul>
    $emailbody += @"
           <li>You may not reuse any of your last $PasswordHistory passwords</li>
          </ul>
         </td>
        </tr>
       </table>
    $emailbody += @"        
           </td>
           <td width="49" align="left" valign="top"><img src="$ImagePath/spacer50.gif" alt="" width="49" height="50"></td>
           <td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
    height="50"></td>
          </tr>
         </table>
         <table id="footer" border="0" cellspacing="0" cellpadding="0" width="655">
          <tr>
           <td><img src="$ImagePath/footer.gif" alt="Description: $ImagePath/footer.gif" width="655" height="81"></td>
          </tr>
         </table>
         <table border="0" cellspacing="0" cellpadding="0" width="655" align="center">
          <tr>
           <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
           <td align="middle" valign="top"><font face="Verdana" size="1" color="#000000"><p>This email was sent by an automated process.
    if ($HelpDeskURL){
    $emailbody += @"               
           If you would like to comment on it, please visit <a href="$HelpDeskURL"><font color="#ff0000"><u>click here</u></font></a>
    $emailbody += @"               
            </p><p style="color: #009900;"><font face="Webdings" size="4">P</font> Please consider the environment before printing this email.</p></font>
           </td>
           <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
          </tr>
         </table>
        </td>
       </tr>
      </table>
     </body>
    </html>
          if (!($demo)){
           $emailto = $accountObj.mail
           if ($emailto){
            Write-Verbose "Sending demo message to $emailto"
            Send-MailMessage -To $emailto -Subject "Your password expires in $DaysTillExpire day(s)" -Body $emailbody -From $EmailFrom -Priority High -BodyAsHtml
            $global:UsersNotified++
           }else{
            Write-Verbose "Can not email this user. Email address is blank"
    } # end function Get-ADUserPasswordExpirationDate
    if ($install){
     Write-Verbose "Install mode"
     Install
    Write-Verbose "Checking for ActiveDirectory module"
    if ((Set-ModuleStatus ActiveDirectory) -eq $false){
     $error.clear()
     Write-Host "Installing the Active Directory module..." -ForegroundColor yellow
     Set-ModuleStatus ServerManager
     Add-WindowsFeature RSAT-AD-PowerShell
     if ($error){
      Write-Host "Active Directory module could not be installed. Exiting..." -ForegroundColor red;
      if ($transcript){Stop-Transcript}
      exit
    Write-Verbose "Getting Domain functional level"
    $global:dfl = (Get-AdDomain).DomainMode
    # Get-ADUser -filter * -properties PasswordLastSet,EmailAddress,GivenName -SearchBase "OU=Users,DC=domain,DC=test" |foreach {
    if (!($PreviewUser)){
     if ($ou){
      Write-Verbose "Filtering users to $ou"
      $users = Get-AdUser -filter * -SearchScope subtree -SearchBase $ou -ResultSetSize $null
     }else{
      $users = Get-AdUser -filter * -ResultSetSize $null
    }else{
     Write-Verbose "Preview mode"
     $users = Get-AdUser $PreviewUser
    if ($demo){
     Write-Verbose "Demo mode"
     # $WhatIfPreference = $true
     Write-Host "`n"
     Write-Host ("{0,-25}{1,-8}{2,-12}" -f "User", "Expires", "Policy") -ForegroundColor cyan
     Write-Host ("{0,-25}{1,-8}{2,-12}" -f "========================", "=======", "===========") -ForegroundColor cyan
    Write-Verbose "Setting event log configuration"
    $evt = new-object System.Diagnostics.EventLog("Application")
    $evt.Source = $ScriptName
    $infoevent = [System.Diagnostics.EventLogEntryType]::Information
    $EventLogText = "Beginning processing"
    $evt.WriteEntry($EventLogText,$infoevent,70)
    Write-Verbose "Getting password policy configuration"
    $DefaultDomainPasswordPolicy = Get-ADDefaultDomainPasswordPolicy
    [int]$MinPasswordLength = $DefaultDomainPasswordPolicy.MinPasswordLength
    # this needs to look for FGPP, and then default to this if it doesn't exist
    [bool]$PasswordComplexity = $DefaultDomainPasswordPolicy.ComplexityEnabled
    [int]$PasswordHistory = $DefaultDomainPasswordPolicy.PasswordHistoryCount
    ForEach ($user in $users){
     Get-ADUserPasswordExpirationDate $user.samaccountname
    Write-Verbose "Writing summary event log entry"
    $EventLogText = "Finished processing $global:UsersNotified account(s). `n`nFor more information about this script, run Get-Help .\$ScriptName. See the blog post at
    http://www.ehloworld.com/318."
    $evt.WriteEntry($EventLogText,$infoevent,70)
    # $WhatIfPreference = $false
    # Remove-ScriptVariables -path $MyInvocation.MyCommand.Name
    Remove-ScriptVariables -path $ScriptPathAndName

    Hi petro_jemes,
    Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
    I hope this helps.

  • PowerShell Scripting help to combine two scripts

    I have a script that helps automate virtual server builds.  The script creates a specification document which is used to perform the actual builds.
    # Spec-And-Build.ps1 - Loops through a directory and performs an
    # end to end specification generation and build on each request in that directory
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$RequestDir,
        [Parameter(Mandatory=$true)]
        [string]$SpecDir,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_CPR,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_VDC,
        [Parameter(Mandatory=$false)]
        [pscredential]$Credential_Admin
    if (!$Credential_CPR) {
        $Credential_CPR = Get-Credential -Message "CPR Domain Credentials."
        if (!$Credential_CPR.UserName.ToUpper().StartsWith("CPR\")) {
            $Credential_CPR = New-Object pscredential(
                ("CPR\" + $Credential_CPR.UserName), $Credential_CPR.Password)
    if (!$Credential_VDC) {
        $Credential_VDC = Get-Credential -Message "VDC Domain Credentials."
        if (!$Credential_VDC.UserName.ToUpper().StartsWith("VDC\")) {
            $Credential_VDC = New-Object pscredential( `
                ("VDC\" + $Credential_VDC.UserName), $Credential_VDC.Password)
    if (!$Credential_Admin) {
        $Credential_Admin = Get-Credential -UserName "Administrator or root" `
            -Message "Enter the Administrator or root password for the new VM. The user name here will be ignored"
    .\Gen-VMSpec-Many.ps1 -RequestDir $RequestDir -SpecDir $SpecDir -Credential_VDC $Credential_VDC
    $caption = "Continue Build"
    $message = "Please validate the generated specification files in $SpecDir - Then click Continue to start build"
    $opContinue = new-Object System.Management.Automation.Host.ChoiceDescription "&Continue","help"
    $opAbort = new-Object System.Management.Automation.Host.ChoiceDescription "&Abort","help"
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($opContinue,$opAbort)
    $answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
    if ($answer -eq 0) {
        .\Build-VM-Many.ps1 -SpecDir $SpecDir -Credential_CPR $Credential_CPR -Credential_VDC $Credential_VDC -Credential_Admin $Credential_Admin
    } else {
        Write-Host "Build step aborted, run Build-VM-Many.ps1 manually to continue."
    This script works well.  Now I need to add a section that adds Active Directory groups to the built servers from the spec document.  I found this script which also works well:
    # Create local group on the local or a remote computer 
    Write-Host -foregroundcolor Yellow 'Admin Privileges Required!' 
    $computerName = Read-Host 'Enter computer name or press <Enter> for localhost' 
    $localGroupName = Read-Host 'Enter local group name' 
    $description = Read-Host 'Enter description for new local group' 
    if ($computerName -eq "") {$computerName = "$env:computername"} 
    if([ADSI]::Exists("WinNT://$computerName,computer")) { 
        $computer = [ADSI]"WinNT://$computerName,computer" 
        $localGroup = $computer.Create("group",$localGroupName) 
        $localGroup.SetInfo() 
        $localGroup.description = [string]$description 
        $localGroup.SetInfo() 
    My question is, how do I make one script from the two?  I am very new to PowerShell scripting.

    Here are the instructions on how to use PowerShell:
    http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx
    Your question is vague and is asking for someone to do this for you.  It is better if you do it yourself and post back with specific questions.
    In the end you have to write and debug the scripts. We will not do this for you but we will answer questions.
    ¯\_(ツ)_/¯

  • Need some help in building a PowerShell Script

    I am in the process of setting up continuous self-auditing on a set of computers that are on a Domain. My company has a restriction on use of USB devices as well as CDs/DVDs. The domain pushes patches but we have been seeing some users that are using (or
    trying to) the network without becoming a part of the domain. My aim is to run a PowerShell script periodically (say, hourly) on each computer on the domain and dump certain parameters to XML / XHTML and then load these onto a web-server that can display the
    results in a (sort of) dashboard to flag anomalies like unauthorised USB use etc.
    I know there must be some commercial products for this but the boss says "No" to a purchase. 
    Am I on the right track or do I need to change my approach? Also, is there a starting scirpt available somewhere so that I can study it for techniques? My major problem is the display part. I am able to dump it into XML and (sort of ) format it but how do
    I collate the data and display it as a web-page is what is bothering me. Help would be deeply appreciated.

    @JRV:
    Users don't have to be domain administrators
    to be able to install software. Local admin is more than enough. ie: I am no admin in the domain of my customer but am allowed to install software
    Although I agree with you, in the sense it would be easier to restrict the users, it doesn't mean that a company has to do it that way; and it certainly doesn't represent the intelligence of an individual. 
    @SarabRSingh:
    What you are asking for is a lot of work, to get the script right (considering the special demands, ie. AV update checking is different depending on the SW) and it might require a lot of resources on the client.
    From what you describe, you want to prevent any USB/Optical Media use. You should consider Group Policies to manage that. http://technet.microsoft.com/en-us/library/bb742376.aspx
    The only part I would script (based on my work environment) is the checking of AV updates (gets tricky because our SW has a hard time forcing the user to update when connected by VPN).
    user log in / out --> group policy: logon/off script writing appending timestamp to a file
    has he/she used any USB device --> if you want to block it: GPO, if you only want to track it: powershell
    Get-WmiObject Win32_USBControllerDevice
    has any new application / software been installed: restrict installation completely with user permissions or: http://social.technet.microsoft.com/Forums/en-US/f4dc8ab9-370b-423e-b65d-1fa46fa9bcc4/powershell-script-to-remotely-audit-computers-on-lan?forum=ITCG
    was the AV: no idea on what you are using (maybe: http://serverfault.com/questions/129611/how-to-detect-when-antivirus-is-out-of-date-with-powershell
    OS updated: WSUS http://technet.microsoft.com/en-us/library/cc708519(v=ws.10).aspx
    If you found this post helpful, please "Vote as Helpful". If it answered your question, remember to "Mark as Answer"
    MCC & PowerShell enthusiast
    http://oliver.lipkau.net/blog

  • Running PowerShell Script to automate the installation of IIS feature - Add-WindowsFeature error, help please

    I'm just learning PS scripting and Chef Programming, so I'm sure I'm missing something simple. I'm trying to run a recipe that is using PS as the interpreter. I've ensured I'm running PS in 64 bit with admin privileges, and have Imported the ServerManager
    module. I even added a line to my script to have it run that first, but am still receiving an error in my script. I'm running this on a VM of Server 2008R2
    Script:
    powershell_script 'Install IIS' do
      code "Import-Module ServerManager -passthru"
      code "Add-WindowsFeature Web-Server"
      guard_interpreter :powershell_script
      not_if "(Get-WindowsFeature -Name Web-Server).Installed"
    end
    Error:
    PS C:\Users\Administrator\chef-repo> chef-apply webserver.rb
    Recipe: (chef-apply cookbook)::(chef-apply recipe)
      * powershell_script[Install IIS] action run
        ================================================================================
        Error executing action `run` on resource 'powershell_script[Install IIS]'
        ================================================================================
        Mixlib::ShellOut::ShellCommandFailed
        Expected process to exit with [0], but received '1'
        ---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat
    None -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
        STDOUT:
        STDERR: The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable
    program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
        ---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat No
    ne -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
        Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Us
    ers/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1
        Resource Declaration:
        # In webserver.rb
          1: powershell_script 'Install IIS' do
          2:   code "Import-Module ServerManager -passthru"
          3:   code "Add-WindowsFeature Web-Server"
          4:   guard_interpreter :powershell_script
          5:   not_if "(Get-WindowsFeature -Name Web-Server).Installed"
          6: end
        Compiled Resource:
        # Declared in webserver.rb:1:in `run_chef_recipe'
        powershell_script("Install IIS") do
          action "run"
          retries 0
          retry_delay 2
          guard_interpreter :powershell_script
          command "\"powershell.exe\" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -Fi
    le \"C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1\""
          backup 5
          returns 0
          code "Add-WindowsFeature Web-Server"
          interpreter "powershell.exe"
          cookbook_name "(chef-apply cookbook)"
          recipe_name "(chef-apply recipe)"
          not_if "(Get-WindowsFeature -Name Web-Server).Installed"
        end
    [2014-12-24T10:29:56-08:00] FATAL: Stacktrace dumped to C:/chef/cache/chef-stacktrace.out
    [2014-12-24T10:29:56-08:00] FATAL: Mixlib::ShellOut::ShellCommandFailed: powershell_script[Install IIS] ((chef-apply coo
    kbook)::(chef-apply recipe) line 1) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0
    ], but received '1'
    ---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None
     -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
    STDOUT:
    STDERR: The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable prog
    ram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    ---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -
    File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
    Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Users/
    ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1

    Hi There,
    We have a application named Microsoft SCOM. That as well requires ISS to be installed. I tried this long back and it worked in powershell. Below is the powershell script i used to install IIS and some specific features from it. Hope it helps in altering
    it and making one of your own script.
    1.  Launch the PowerShell command
    prompt
     Run this command
    Import-Module ServerManager
    3. Press Enter
    4. Run this
    command
    Add-WindowsFeature NET-Framework-Core,Web-Metabase,Web-WMI,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Filtering,Web-Windows-Auth,
    Web-Mgmt-Console –restart
    Gautam.75801

  • Help to modify MultiCurrencyTrans.LGL script

    We are working on this budgeting scenario:
    For the input schedules, SKUs are budgeted per Entities. Budgeted sales price per SKU could be in any currency (currencies are chosen by the end user based on agreement with the sales department). Sample data are the following:
    ENTITY 1
    SKU 1
    USD (or any currency chosen by the end user)
    ENTITY 1
    SKU 2
    JPY (or any currency chosen by the end user)
    ENTITY 2
    SKU 1
    EURO (or any currency chosen by the end user)
    ENTITY 2
    SKU 2
    SGD (or any currency chosen by the end user)
    Report output should have the budgeted original currencies per SKU per Entity as well as translated currencies into EURO.
    In the SAP BPC MultiCurrencyTrans.LGL script, the currency translation works for a single LC to multiple currencies. However, in the scenario above, it works the other way around, i.e. data are in “multiple LCs” (i.e. sales price) to be translated to a single currency (i.e. EURO).
    Can you help me in modifying the LGL script to meet the requirement described above?

    One other thought that's a blend of the two above and would probably do what you're looking for is:
    1.  I would do this as a separate application from any financial reporting applications you my have and push the LC over if needed for reporting.
    2. Keep the currency translation dimension on the entity dimension with the correct currency property to identify what it's LC currency is.
    3. Create the application with a standalone currency dimension (not used in other apps) that has all the members from the InputCurrency dimension in your rate application + add in LC.
    4. Have users select the specifc currency that they're entering to (never LC).  So they'd pick Entity1, SKU1, JPY as an input point.
    5. Write a custom FXTrans process that converts from the input currency to LC based on the entity.  I'd run this as part of default logic.
    6.  Use the standard FXTrans process then to convert from LC into your reporting currency of EURO.  If this is the only reporting currency then the single currency FXTrans would work.  You'd want to make sure the code ONLY goes from LC to EURO.
    So, users would enter JPY which would translate back to the LC of the entity and write the value to LC.  Then you'd translate from LC to EURO for reporting.  In cases where the  data entry is done in EURO, you'd go from EURO > LC > EURO but that shouldn't matter as long as you don't make any changes to the translation rates between the two processes.  HOWEVER, you need to be certain that if you change translation rates after data entry has occured that the process to go from input currency to LC is run so the LC values are correctly calculated or you would get different results when going to your reporting currency.

  • Help using SMLets in workflow powershell script

    Hello,
    I have written a powershell script in a workflow to help me perform a process. The idea is this: We have an extended Incident class and a custom RMA class, users will sometimes need to launch an RMA from an incident, but never an incident from an RMA or
    an RMA by itself. Therefore, source cardinality I assume is 1 and target cardinality is 2 (unlimited). The RMA NEEDS TO BE ASSOCIATED (related) to the ID # of the Incident Request. So, if you click on the Incident and go to related items, you should see the
    RMA id # there, and when you go to the related items of the RMA, you should see the appropriate IR # there. The workflow is launched by trigger: when an object of the RMA class is created.
    The workflow contains the following powershell script:
    # Load the SMlets module
    Import-Module SMlets
    # Get Date
    $date = ((Get-Date).AddDays(-1));
    # Set ClassName
    $ClassName = Get-SCSMClass -Name Flexity.RMA.Class;
    # Get the RMA Class
    $RMAClass = Get-SCSMObject -Class $ClassName | where{$_.CreatedDate -gt $date};
    # Set DisplayName, Title and Description to RMAx
    foreach ($RMA in $RMAClass)
     {$RMANumber = $RMA.RMA_ID; $RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; “Title” =  $RMANumber; ”Description” =  $RMANumber;  
    So I can get the RMA objects created, and properly name them so they show up as RMA{#} but still have not figured out how to get the parent incident and relate it to the appropriate RMA #... Any help would be greatly appreciated!!!!!

    @Anders
    For Service Manager 2010, numbers larger than 1 in a cardinality statement are evaluated as “unlimited” when an MP is imported into Service Manager. This means that MaxCardenality=“2” is the same as MaxCardenality=“2147483647”. Has this changed from 2010
    to 2012?
    @Thomas
    You are indeed correct but I didn't receive any response in there from my last post so I thought it was dead by now. I have also progressed MUCH further from when I had posted that question, so I figured I should just make it a new topic as the topic of
    the question has become much more specific. I will link this post in there to be used as reference.
    I actually ended up figuring this out, let me know what you guys think and if it can be optimized in any way, or if you see any error checking I should add in somewhere.
    Thank you all for your help, especially with your detailed responses Thomas
    My original idea was to have a workflow and that workflow got launched when an object of the RMA class was created, regardless of HOW it was launched through console task or custom control or whatever. However, I ended up using a console task, which when clicked
    launches my script :)
    Code:
    # Creates a variable called IncidentID and points Incident # to it for use within the script
    Param([string]$IncidentID)
    # Load the SMlets module
    Import-Module SMlets
    # Get the Incident Class
    $IncClass = Get-SCSMClass -Name System.WorkItem.Incident$
    # Get the RMA Class
    $RMAClass = Get-SCSMClass -Name flexity.RMA.class
    # Build the Filter String
    $FilterStr = "ID -eq " + $IncidentID
    # Find the Incident we need to link to an RMA
    $Inc = Get-SCSMObject -Class $IncClass -Filter $FilterStr
    $RMAIncText = ["Linked to Incident " + $Inc.ID + ""]
    $RMADescription = $RMAIncText
    New-SCSMObject -Class $RMAClass -PropertyHashtable (@{Title = $Inc.Title; Description = $RMADescription})
    # Find the new RMA to be linked
    $FilterStr = "Description -eq '$RMADescription'"
    $RMA = Get-SCSMObject -Class $RMAClass -Filter $FilterStr
    #Set RMA Number Variable
    $RMANumber = $RMA.RMA_ID;
    #Clean up DisplayName, Title and Description 
    $RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; "Title" =  $RMANumber; "Description" =  $RMANumber;   }
    # Create the relationship between the two items
    $RWIClass = Get-SCSMRelationshipClass -Name System.WorkItemRelatesToWorkItem$
    New-SCSMRelationshipObject -Relationship $RWIClass -Source $Inc -Target $RMA -Bulk
    New-SCSMRelationshipObject -Relationship $RWIClass -Source $RMA -Target $Inc -Bulk
    # Unload the SMlets module
    Remove-Module SMlets

  • Powershell script help

    mattmcnabb wrote:
    set-aduser -scriptpath $null
    Too easy.  Thanks!

    I want to remove the log in script from a user but I do not want to use AD modify as I am going to have to do this slowly. I found the set-aduser -logon directory to remove the home folder but what is the powershell script to change this to blank. 
    This topic first appeared in the Spiceworks Community

  • Powershell script to help fix broken WMI on remote servers/computer.

    I have a number of servers/computers that I am not able to update due to broken WMI. Does anyone out there have a Powershell script that will stop the WMI service, rename the repository and logs folders, then restart the WMI service again?
    I created a script to stop the service, but it will not allow me to rename the folders (tells me access denied). If I dameware into the pc and log in with my admin credentials I have no issues manually doing the above steps, but there has to be an easier
    way!
    Any help would be greatly appreciated.

    To remotely rename folders you must use an admin account on the remote system. The folder must not be protected the system and you cannot us WMI to rename the folder.
    You may have to restart the system after setting WMI to manual start as it can have locks and it may not shutdown cleanly.
    ¯\_(ツ)_/¯

  • Looking for help with PowerShell script to delete folders in a Document Library

    I'd like to create a PowerShell script to delete old folders in a Document library that are over 30 days old. Has anyone created something like this?
    Orange County District Attorney

    Hello Sid:
    I am trying to do the same and Iam running the script to delete the subfolders inside a folder  but I have some errors. 
    Could you please take a look?
    _______Script________
    $web = Get-SPWeb -Identity https://myportal.mydomain.com
    $list = $web.GetList("ar_mailingactivity")
    $query =  New-Object Microsoft.SharePoint.SPQuery 
    $camlQuery = '<Where><And><Eq><FieldRef Name="ContentType" /><Value Type="Computed">Folder</Value></Eq><Leq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-30" /></Value></Leq></And></Where>'
    $query.Query = $camlQuery
    $items = $list.GetItems($query)
    for ($intIndex = $items.Count - 1; $intIndex -gt -1; $intIndex--)
       $items.Delete($intIndex);
    ________Errors_______
    Unable to index into an object of type System.Management.Automation.PSMethod.
    At C:\Script.ps1:2 char:22
    + $list =$webGetList <<<< "ar_mailingactivity"]
    + CategoryInfo
    :InvalidOperation: (ar_mailingactivity:String) [], RuntimeException
    + FullyQualifiedErrorID
    :CannotIndex
    You cannot call a method on  a null-valued expression.
    At c:\Script.ps1:6 char:24
    + $items = $list.GetItems <<<< ($query)
    + CategoryInfo
    :InvalidOperation: (GetItems:String) [], RuntimeException
    + FullyQualifiedErrorID
    :InvokeMethodOnNull

  • How to Parse this XML File and require below mentioned value as output using powershell script

    Need values for below as an output for below xml file so help me with the script:
    Under Criteria Tag-
    TimeStamp Display Value
    OID corresponding to display value for nodes "Criterion"
    Under Report Body Tag--
    name in Report Section and OID value
    <?xml version="1.0" encoding="UTF-8"?>
    <ReportOutput>
        <ReportHead>
            <Report name="Execution Action" type="detailedchanges_rpt">
                <Description></Description>
            </Report>
            <Criteria>
                <TimestampCriterion name="date" displayvalue="08/10/14 23:08">
                    <Timestamp displayvalue="08/10/14 23:08">1412780929000</Timestamp>
                </TimestampCriterion>
                <MatchCriterion name="approvalId" displayvalue="Not applied" operator="contains" />
                <MatchCriterion name="promotionComment" displayvalue="Not applied" operator="contains" />
                <SelectCriterion name="changeWindow" displayvalue="Not applied" />
                <SelectCriterion name="auditEvents" displayvalue="(Any)">
                    <String>auditEventAny</String>
                </SelectCriterion>
                <SelectCriterion name="attributeDisplay" displayvalue="Changed attributes">
                    <String>changed</String>
                </SelectCriterion>
                <SelectCriterion name="versionCompare" displayvalue="Version with current baseline">
                    <String>disabled</String>
                </SelectCriterion>
                <BooleanCriterion name="showContentDiff" displayvalue="No">
                    <Boolean value="false" />
                </BooleanCriterion>
                <BooleanCriterion name="displayUsers" displayvalue="No">
                    <Boolean value="false" />
                </BooleanCriterion>
                <BooleanCriterion name="displayPackages" displayvalue="No">
                    <Boolean value="false" />
                </BooleanCriterion>
                <BooleanCriterion name="displayCustomProperties" displayvalue="No">
                    <Boolean value="false" />
                </BooleanCriterion>
                <BooleanCriterion name="strictPackageMatch" displayvalue="No">
                    <Boolean value="false" />
                </BooleanCriterion>
                <BooleanCriterion name="displayCriteriaAtEnd" displayvalue="No">
                    <Boolean value="false" />
                </BooleanCriterion>
                <SelectCriterion name="elementExists" displayvalue="Not applied" />
                <IntegerCriterion name="maxLinesPerBlock" displayvalue="10">
                    <Integer>10</Integer>
                </IntegerCriterion>
                <NodesCriterion name="nodes" displayvalue="TripwireENT.demo.net">
                    <OID>-1y2p0ij32e8bw:-1y2p0ij32e7cu</OID>
                </NodesCriterion>
                <MatchCriterion name="nodeName" displayvalue="Not applied" operator="contains" />
                <CustomPropertiesCriterion name="nodeProps" displayvalue="Not applied" />
                <RulesCriterion name="rules" displayvalue="Critical System Files">
                    <OID>-1y2p0ij32e7q2:-1y2p0ij31snh6</OID>
                </RulesCriterion>
                <MatchCriterion name="ruleName" displayvalue="Not applied" operator="contains" />
                <MatchCriterion name="elementName" displayvalue="Not applied" operator="contains" />
                <CustomPropertiesCriterion name="elementProps" displayvalue="Not applied" />
                <CustomPropertiesCriterion name="versionProps" displayvalue="Not applied" />
                <AttributesCriterion name="attributes" displayvalue="Not applied">
                    <Integer name=".missingImpliesFailure">1</Integer>
                </AttributesCriterion>
                <ContentCriterion name="content" displayvalue="Not applied" />
                <MatchCriterion name="auditEventUserName" displayvalue="Not applied" operator="contains" />
                <IntegerCriterion name="changeType" displayvalue="Added, Modified, Removed">
                    <Integer>7</Integer>
                </IntegerCriterion>
                <SeverityRangeCriterion name="severity" displayvalue="1 - 10000">
                    <Integer name="min">1</Integer>
                    <Integer name="max">10000</Integer>
                </SeverityRangeCriterion>
                <BooleanCriterion name="currentVersionsOnly" displayvalue="Yes">
                    <Boolean value="true" />
                </BooleanCriterion>
                <TimeRangeCriterion name="timeRange" displayvalue="All time" />
                <PackagesCriterion name="packages" displayvalue="Not applied" />
                <SortCriterion name="sortNodes" displayvalue="Name, ascending" isascending="true">
                    <String>name</String>
                </SortCriterion>
                <SortCriterion name="sortRules" displayvalue="Name, ascending" isascending="true">
                    <String>name</String>
                </SortCriterion>
                <SortCriterion name="sortElements" displayvalue="Name, ascending" isascending="true">
                    <String>name</String>
                </SortCriterion>
                <SortCriterion name="sortVersions" displayvalue="Date, descending" isascending="false">
                    <String>date</String>
                </SortCriterion>
            </Criteria>
        </ReportHead>
        <ReportBody>
            <ReportSection name="TripwireENT.demo.net" category="node">
                <OID>-1y2p0ij32e8bw:-1y2p0ij32e7cu</OID>
                <String name="typeName">Windows Server</String>
                <ReportSection name="Critical System Files" category="rule">
                    <OID>-1y2p0ij32e7q2:-1y2p0ij31snh6</OID>
                    <String name="typeName">Windows File System Rule</String>
                    <ReportSection name="C:\Temp" category="element">
                        <OID>-1y2p0ij32e8dr:-1y2p0ij32e586</OID>
                        <ReportSection name="08/10/14 22:48" category="version">
                            <OID>-1y2p0ij32e8du:-1y2p0ij32e3ho</OID>
                            <Integer name="changeType">1</Integer>
                            <String name="changeTypeName">Added</String>
                            <Integer name="severity">10000</Integer>
                            <String name="severityName">High</String>
                            <Timestamp name="changeTime" displayvalue="08/10/14 22:48">1412779682000</Timestamp>
                            <String name="approvalId"></String>
                            <ReportSection name="attributes" category="attributes">
                                <ReportSection name="DACL" category="added">
                                    <String name="observed">Inherits Entries: true
    NT AUTHORITY\SYSTEM, Access Allowed:
     Standard rights:
      Full Control
      Modify
      Read &amp; Execute
      List Folder Contents
      Read
      Write
      Delete
      Read Control
      Write DAC
      Write Owner
      Synchronize
     Specific rights:
      Full Control
      Traverse Folder / Execute File
      List Folder / Read Data
      Read Attributes
      Read Extended Attributes
      Create Files / Write Data
      Create Folders / Append Data
      Write Attributes
      Write Extended Attributes
      Directory Delete Child
      Read Permissions
      Change Permissions
      Take Ownership
     Header flags:
      Object Inherit
      Container Inherit
      Inherited
    BUILTIN\Administrators, Access Allowed:
     Standard rights:
      Full Control
      Modify
      Read &amp; Execute
      List Folder Contents
      Read
      Write
      Delete
      Read Control
      Write DAC
      Write Owner
      Synchronize
     Specific rights:
      Full Control
      Traverse Folder / Execute File
      List Folder / Read Data
      Read Attributes
      Read Extended Attributes
      Create Files / Write Data
      Create Folders / Append Data
      Write Attributes
      Write Extended Attributes
      Directory Delete Child
      Read Permissions
      Change Permissions
      Take Ownership
     Header flags:
      Object Inherit
      Container Inherit
      Inherited
    BUILTIN\Users, Access Allowed:
     Standard rights:
      Read &amp; Execute
      List Folder Contents
      Read
      Read Control
      Synchronize
     Specific rights:
      Traverse Folder / Execute File
      List Folder / Read Data
      Read Attributes
      Read Extended Attributes
      Read Permissions
     Header flags:
      Object Inherit
      Container Inherit
      Inherited
    BUILTIN\Users, Access Allowed:
     Specific rights:
      Create Folders / Append Data
     Header flags:
      Container Inherit
      Inherited
    BUILTIN\Users, Access Allowed:
     Specific rights:
      Create Files / Write Data
     Header flags:
      Container Inherit
      Inherited
    CREATOR OWNER, Access Allowed:
     Generic rights:
      Generic All
     Specific rights:
      Full Control
      Traverse Folder / Execute File
      List Folder / Read Data
      Read Attributes
      Read Extended Attributes
      Create Files / Write Data
      Create Folders / Append Data
      Write Attributes
      Write Extended Attributes
      Directory Delete Child
      Read Permissions
      Change Permissions
      Take Ownership
     Header flags:
      Object Inherit
      Container Inherit
      Inherit Only
      Inherited
    </String>
                                </ReportSection>
                                <ReportSection name="Group" category="added">
                                    <String name="observed">TRIPWIREENT\None</String>
                                </ReportSection>
                                <ReportSection name="Owner" category="added">
                                    <String name="observed">BUILTIN\Administrators</String>
                                </ReportSection>
                                <ReportSection name="Read-Only" category="added">
                                    <String name="observed">false</String>
                                </ReportSection>
                                <ReportSection name="SACL" category="added">
                                    <String name="observed">(null)</String>
                                </ReportSection>
                                <ReportSection name="Type" category="added">
                                    <String name="observed">Directory</String>
                                </ReportSection>
                            </ReportSection>
                        </ReportSection>
                    </ReportSection>
                    <ReportSection name="C:\Windows\System32\drivers\etc\hosts" category="element">
                        <OID>-1y2p0ij32e8dr:-1y2p0ij32e4kp</OID>
                        <ReportSection name="08/10/14 23:08" category="version">
                            <OID>-1y2p0ij32e8du:-1y2p0ij32e3hk</OID>
                            <Integer name="changeType">2</Integer>
                            <String name="changeTypeName">Modified</String>
                            <Integer name="severity">10000</Integer>
                            <String name="severityName">High</String>
                            <Timestamp name="changeTime" displayvalue="08/10/14 23:08">1412780929000</Timestamp>
                            <String name="approvalId"></String>
                            <ReportSection name="attributes" category="attributes">
                                <ReportSection name="SHA-1" category="modified">
                                    <String name="expected">de375d8a456a7345323babee88975ca567a2d5c4</String>
                                    <String name="observed">3c5520382f91cb1cd898fee2da4eba3fa338d982</String>
                                </ReportSection>
                                <ReportSection name="Size" category="modified">
                                    <String name="expected">829</String>
                                    <String name="observed">854</String>
                                </ReportSection>
                            </ReportSection>
                        </ReportSection>
                    </ReportSection>
                </ReportSection>
            </ReportSection>
            <ReportSection name="reportTotals" category="reportTotals">
                <Integer name="summary.nodeCount">1</Integer>
                <Integer name="summary.ruleCount">1</Integer>
                <Integer name="summary.elementCount">2</Integer>
            </ReportSection>
        </ReportBody>
    </ReportOutput>

    Hi Ritehere,
    I know this is simple but am beginner in Powershell Script so I was looking for logic to go through however the output you provided is not what i am looking for and your script is too complicated, as under timestamp i wanted display value and correspoding
    to display value the OID name and then name value correspoding to that OID. May be u got it wrong.
    Thanks anyways.

Maybe you are looking for

  • Adobe Bridge CS5 in windows 7 not working?

    Adobe Bridge CS5 in windows 7 not working. I was using bridge perfectly for last 2 years. It stops working since 3 days. I tried to install updates. Showing some error to install. Tried to install creative cloud..again some error. Error code : 82 Cou

  • Installing CCMS on a new system. System entry not found in RZ20CEN aftr reg

    Hi Guys, I am trying to install CCMS for our systems. I have made all the configurations as per the "Monitoring Setup Guide (CEN SAP Net Weaver7.0 SPS 13)" document and refered all the help.sap.com doc's for configuring ccms. I have registered the sy

  • Why are my placed drawings pixeled and blurry?

    I've tried to place drawings (originally from a pdf file) in .ai, .jpg. .pdf and .eps format in an indesign document version CS5. They all appear blurry, despite looking nice and sharp in illustrator. What am I doing wrong?

  • I'm getting green flashes when I compress my mpeg2 files....

    Does anyone know why I'm getting green flashes when I compress my movie for DVD Studio Pro? It plays (relatively) fine in FCP, but when I compress it (using Compressor) for DVD output I got a movie full of green flashes. It's really annoying and I ca

  • How to make a payment term as Default in Credit note in certain Sales Orgs.

    Hello experts, Kindly provide your valuable inputs as How can i make the payment terms( say AU00 =Due Immediately) default for  a few sales organizations. As checked, Depending on the type of Credit notes( i.e. WITH OR WITHOUT reference to an invoice