Modify Powershell Script

Hello
How can I modify this script to target all Users OU in one domain to move all disabled accounts from each Users OU to move to the Disabled Users OU?
Search-ADAccount –AccountDisabled –UsersOnly –SearchBase “OU=Users,OU=test,OU=domain,DC=domain,DC=com”  | Move-ADObject –TargetPath “OU=Disabled Users,DC=domain,DC=com”
The above script will work for but only for one OU, I need it to target all OU=Users OU.
Thanks

Hi Rover,
I‘m writing to check if the suggestions were helpful, if you have any questions, please feel free to let me know.
If you have any feedback on our support, please click here.
Best Regards,
Anna
TechNet Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

Similar Messages

  • 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.

  • Powershell script to modify DNS not returning errors

    I've modified a script to make DNS changes given a name/IP combo from a CSV file and it seems to be working, but is not throwing any errors (which I had thought it would do, but doesn't)
    ## Directions:
    ## Script Requires DnsShell 0.4.4 http://dnsshell.codeplex.com/
    ## Script Uses Get-Dns and New-DnsRecord
    ## csv file must be in following format including the proper first line headers
    ## Name,IPAddress
    ## eample_a_record,127.0.0.1
    Write-Host "Enter Name the Path to the CSV File>"
    $CSV = read-host
    Write-Host "Enter Name the DNS Server>"
    $ServerName = read-host
    Write-Host "Enter the Domain example: domain.local>"
    $ForwardLookupZone = read-host
    $filename = "D_ERRLOG{0:yyyyMMdd-HHmm}.txt" -f (Get-Date) #error Log
    Write-Host "Enter The Reverse Domain Octet example 168.192 or 10 for 10.in-addr.arpa.>"
    $TReverseLookupZone = read-host
    $ReverseLookupZone = $TReverseLookupZone + ".in-addr.arpa."
    # Import CSV and create A record
    Import-Csv $CSV | ForEach-Object{
    $record = get-dnsrecord -name $_.name -recordtype A -zonename $forwardlookupzone -Server $ServerName
    if ($record.name) {get-dnsrecord -name $_.name -recordtype A -zonename $forwardlookupzone -Server $ServerName | Remove-DnsObject -force | out-file ./$filename -Append}
    New-DnsRecord -name $_.name -recordtype A -zonename $forwardlookupzone -IPaddress $_.IPAddress -Server $ServerName | out-file ./$filename -Append
    #create reverse record
    New-DnsRecord -Name $_.IPAddress -Hostname ($_.name + '.' + $forwardlookupzone) -Zonename $ReverseLookupZone -Type PTR -Server $ServerName | out-file ./$filename -Append
    Write-Host -foreground "yellow" "Any Errors will be in the file $filename"
    The out-file is blank, every time. I've even forced errors but it's still blank.
    Any ideas? 
    Thank you.
    [email protected]

    Hi,
    Just checking in to see if the suggestion was helpful. Please let us know if you would like further assistance.
    TechNet Subscriber Support
    If you are
    TechNet Subscription
    user and have any feedback on our support quality, please send your feedback
    here.
    Regards, Yan Li

  • Please assist with modifying this script to read in a list of servers and output results to excel

    Hello,
    I have an excellent script written by Brian Wilhite to gather the last logged in user using Powershell.
    http://gallery.technet.microsoft.com/scriptcenter/Get-LastLogon-Determining-283f98ae/view/Discussions#content
    My Powershell Fu is stumbling to modify this script to the following requirements:
    Currently the script must be loaded first into Powershell, then it can be executed.  I would rather edit the script in my Powershell ISE, add the .txt file to the script itself that gives a list of the servers I need to scan.  Then when I
    press Run Script in my ISE it executes.
    I would also like to output the results of the file to excel (.xls or .csv will do).  Currently the results look as follows:
    Computer : SVR01
    User : WILHITE\BRIAN
    SID : S-1-5-21-012345678-0123456789-012345678-012345
    Time : 9/20/2012 1:07:58 PM
    CurrentlyLoggedOn : False
    I would prefer it shows up like so:
    Computer User SID Time Currently LoggedOn
    SVR01 WILHITE\BRIAN S-1xxx 9/20/2012 1:07:58 PM FalseSRV02 WILHITE\BRIAN S-2xxx 9/26/2014 10:00:00 AM True
    Any help you can provide would be greatly appreciated.  I'll add the full script to the end of this post.
    Thank you.
    Function Get-LastLogon
    <#
    .SYNOPSIS
    This function will list the last user logged on or logged in.
    .DESCRIPTION
    This function will list the last user logged on or logged in. It will detect if the user is currently logged on
    via WMI or the Registry, depending on what version of Windows is running on the target. There is some "guess" work
    to determine what Domain the user truly belongs to if run against Vista NON SP1 and below, since the function
    is using the profile name initially to detect the user name. It then compares the profile name and the Security
    Entries (ACE-SDDL) to see if they are equal to determine Domain and if the profile is loaded via the Registry.
    .PARAMETER ComputerName
    A single Computer or an array of computer names. The default is localhost ($env:COMPUTERNAME).
    .PARAMETER FilterSID
    Filters a single SID from the results. For use if there is a service account commonly used.
    .PARAMETER WQLFilter
    Default WQLFilter defined for the Win32_UserProfile query, it is best to leave this alone, unless you know what
    you are doing.
    Default Value = "NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'"
    .EXAMPLE
    $Servers = Get-Content "C:\ServerList.txt"
    Get-LastLogon -ComputerName $Servers
    This example will return the last logon information from all the servers in the C:\ServerList.txt file.
    Computer : SVR01
    User : WILHITE\BRIAN
    SID : S-1-5-21-012345678-0123456789-012345678-012345
    Time : 9/20/2012 1:07:58 PM
    CurrentlyLoggedOn : False
    Computer : SVR02
    User : WILIHTE\BRIAN
    SID : S-1-5-21-012345678-0123456789-012345678-012345
    Time : 9/20/2012 12:46:48 PM
    CurrentlyLoggedOn : True
    .EXAMPLE
    Get-LastLogon -ComputerName svr01, svr02 -FilterSID S-1-5-21-012345678-0123456789-012345678-012345
    This example will return the last logon information from all the servers in the C:\ServerList.txt file.
    Computer : SVR01
    User : WILHITE\ADMIN
    SID : S-1-5-21-012345678-0123456789-012345678-543210
    Time : 9/20/2012 1:07:58 PM
    CurrentlyLoggedOn : False
    Computer : SVR02
    User : WILIHTE\ADMIN
    SID : S-1-5-21-012345678-0123456789-012345678-543210
    Time : 9/20/2012 12:46:48 PM
    CurrentlyLoggedOn : True
    .LINK
    http://msdn.microsoft.com/en-us/library/windows/desktop/ee886409(v=vs.85).aspx
    http://msdn.microsoft.com/en-us/library/system.security.principal.securityidentifier.aspx
    .NOTES
    Author: Brian C. Wilhite
    Email: [email protected]
    Date: "09/20/2012"
    Updates: Added FilterSID Parameter
    Cleaned Up Code, defined fewer variables when creating PSObjects
    ToDo: Clean up the UserSID Translation, to continue even if the SID is local
    #>
    [CmdletBinding()]
    param(
    [Parameter(Position=0,ValueFromPipeline=$true)]
    [Alias("CN","Computer")]
    [String[]]$ComputerName="$env:COMPUTERNAME",
    [String]$FilterSID,
    [String]$WQLFilter="NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'"
    Begin
    #Adjusting ErrorActionPreference to stop on all errors
    $TempErrAct = $ErrorActionPreference
    $ErrorActionPreference = "Stop"
    #Exclude Local System, Local Service & Network Service
    }#End Begin Script Block
    Process
    Foreach ($Computer in $ComputerName)
    $Computer = $Computer.ToUpper().Trim()
    Try
    #Querying Windows version to determine how to proceed.
    $Win32OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
    $Build = $Win32OS.BuildNumber
    #Win32_UserProfile exist on Windows Vista and above
    If ($Build -ge 6001)
    If ($FilterSID)
    $WQLFilter = $WQLFilter + " AND NOT SID = `'$FilterSID`'"
    }#End If ($FilterSID)
    $Win32User = Get-WmiObject -Class Win32_UserProfile -Filter $WQLFilter -ComputerName $Computer
    $LastUser = $Win32User | Sort-Object -Property LastUseTime -Descending | Select-Object -First 1
    $Loaded = $LastUser.Loaded
    $Script:Time = ([WMI]'').ConvertToDateTime($LastUser.LastUseTime)
    #Convert SID to Account for friendly display
    $Script:UserSID = New-Object System.Security.Principal.SecurityIdentifier($LastUser.SID)
    $User = $Script:UserSID.Translate([System.Security.Principal.NTAccount])
    }#End If ($Build -ge 6001)
    If ($Build -le 6000)
    If ($Build -eq 2195)
    $SysDrv = $Win32OS.SystemDirectory.ToCharArray()[0] + ":"
    }#End If ($Build -eq 2195)
    Else
    $SysDrv = $Win32OS.SystemDrive
    }#End Else
    $SysDrv = $SysDrv.Replace(":","$")
    $Script:ProfLoc = "\\$Computer\$SysDrv\Documents and Settings"
    $Profiles = Get-ChildItem -Path $Script:ProfLoc
    $Script:NTUserDatLog = $Profiles | ForEach-Object -Process {$_.GetFiles("ntuser.dat.LOG")}
    #Function to grab last profile data, used for allowing -FilterSID to function properly.
    function GetLastProfData ($InstanceNumber)
    $Script:LastProf = ($Script:NTUserDatLog | Sort-Object -Property LastWriteTime -Descending)[$InstanceNumber]
    $Script:UserName = $Script:LastProf.DirectoryName.Replace("$Script:ProfLoc","").Trim("\").ToUpper()
    $Script:Time = $Script:LastProf.LastAccessTime
    #Getting the SID of the user from the file ACE to compare
    $Script:Sddl = $Script:LastProf.GetAccessControl().Sddl
    $Script:Sddl = $Script:Sddl.split("(") | Select-String -Pattern "[0-9]\)$" | Select-Object -First 1
    #Formatting SID, assuming the 6th entry will be the users SID.
    $Script:Sddl = $Script:Sddl.ToString().Split(";")[5].Trim(")")
    #Convert Account to SID to detect if profile is loaded via the remote registry
    $Script:TranSID = New-Object System.Security.Principal.NTAccount($Script:UserName)
    $Script:UserSID = $Script:TranSID.Translate([System.Security.Principal.SecurityIdentifier])
    }#End function GetLastProfData
    GetLastProfData -InstanceNumber 0
    #If the FilterSID equals the UserSID, rerun GetLastProfData and select the next instance
    If ($Script:UserSID -eq $FilterSID)
    GetLastProfData -InstanceNumber 1
    }#End If ($Script:UserSID -eq $FilterSID)
    #If the detected SID via Sddl matches the UserSID, then connect to the registry to detect currently loggedon.
    If ($Script:Sddl -eq $Script:UserSID)
    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"Users",$Computer)
    $Loaded = $Reg.GetSubKeyNames() -contains $Script:UserSID.Value
    #Convert SID to Account for friendly display
    $Script:UserSID = New-Object System.Security.Principal.SecurityIdentifier($Script:UserSID)
    $User = $Script:UserSID.Translate([System.Security.Principal.NTAccount])
    }#End If ($Script:Sddl -eq $Script:UserSID)
    Else
    $User = $Script:UserName
    $Loaded = "Unknown"
    }#End Else
    }#End If ($Build -le 6000)
    #Creating Custom PSObject For Output
    New-Object -TypeName PSObject -Property @{
    Computer=$Computer
    User=$User
    SID=$Script:UserSID
    Time=$Script:Time
    CurrentlyLoggedOn=$Loaded
    } | Select-Object Computer, User, SID, Time, CurrentlyLoggedOn
    }#End Try
    Catch
    If ($_.Exception.Message -Like "*Some or all identity references could not be translated*")
    Write-Warning "Unable to Translate $Script:UserSID, try filtering the SID `nby using the -FilterSID parameter."
    Write-Warning "It may be that $Script:UserSID is local to $Computer, Unable to translate remote SID"
    Else
    Write-Warning $_
    }#End Catch
    }#End Foreach ($Computer in $ComputerName)
    }#End Process
    End
    #Resetting ErrorActionPref
    $ErrorActionPreference = $TempErrAct
    }#End End
    }# End Function Get-LastLogon

     This should work:
    Get-LastLogon -Computername (Get-content .\Servers.txt) | Export-CSV .\Output.csv -NoTypeInformation
    I just tested it on my test domain and it did the trick.

  • 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.

  • Powershell script to count number of list and library items in site collection

    We are identifying large lists in our 2010 SP environment and I'm attempting to write code to output the total number of list items in a site collection.   I'm using the code below but it only displays column data for title and url. 
    What do I need to add so it can count the number of items in each sharepoint list and library? 
    Get-SPSite -WebApplication http://sharepoint -Limit All |
       Select -ExpandProperty AllWebs |
       Select -ExpandProperty Lists |
       Select ParentWebUrl, Title
    I'm referencing
    http://sharepointpromag.com/sharepoint/windows-powershell-scripts-sharepoint-info-files-pagesweb-parts

    Please find belwo script, it will iterarte through all the folder/Subfoder to get the item counts from all list and library, you can modify this script to run this at site collection scope:
    Note: save the script in .ps1 file and execute the script as described below to get log file, it will save the log file out.txt in seleted directory:
    e.g.PS D:\PowershellScripts> .\ListItemCount.ps1 > out.txt
    $SPWebApp = Get-SPWebApplication "http://weburl.com/"
    foreach ($SPSite in $SPWebApp.Sites)
    if ($SPSite -ne $null)
    foreach ($SPWeb in $SPSite.AllWebs)
    foreach ($list in $SPWeb.Lists)
    $ListURL = $SPWeb.url + "/" + $list.RootFolder.Url
    Write-Output $ListURL
    [Microsoft.SharePoint.SPQuery]$query = New-Object Microsoft.SharePoint.SPQuery
    #$query.Folder = fldr;
    #Recursive Scope....
    $query.ViewAttributes = "Scope='Recursive'"
    $allitems = $list.GetItems($query);
    $filecount = $allitems.Count;
    Write-Output " No of item: " $filecount
    if ($SPWeb -ne $null)
    $SPWeb.Dispose()
    if ($SPSite -ne $null)
    $SPSite.Dispose()
    You can update the code to get any specific list type item count, using if($list.BaseType -eq "DocumentLibrary") condition:
    if($list.BaseType -eq "DocumentLibrary")
    $ListURL = $SPWeb.url + "/" + $list.RootFolder.Url
    Write-Output $ListURL
    [Microsoft.SharePoint.SPQuery]$query = New-Object Microsoft.SharePoint.SPQuery
    #$query.Folder = fldr;
    #Recursive Scope....
    $query.ViewAttributes = "Scope='Recursive'"
    $allitems = $list.GetItems($query);
    $filecount = $allitems.Count;
    Write-Output " No of item: " $filecount
    if ($SPWeb -ne $null)
    $SPWeb.Dispose()
    If my contribution helps you, please click Mark As Answer on that post and Vote as Helpful
    Thanks, ShankarSingh

  • Powershell script to change the a column value of all documents in a site.

    Hi,
    I need a powershell script to change the value of a column (a site column which has been added to all document libraries) in all documents in a site,
    For example: 
    -column 1 is a site column added to all libraries
    the value of column 1 of all documents under this site: http://intranet.doman/ex1 should be equal to V1
    the value of column 1 of all documents under this site: http://intranet.doman/ex2 should be equal to V2
    So, if I can write a powershell script to change the value of all documents in a site, I can modify it for different site that I have and run it for each of them individually,

    cls
    # Is dev version?
    $dev = $false
    # Configuration
    $termStore = "Managed Metadata Service"
    $group = "G1"
    $subjectMatterTermSetName = "Subject Matter"
    # Check if SharePoint Snapin is loaded
    if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
         Add-PSSnapin Microsoft.SharePoint.PowerShell
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy") | Out-Null
    function GetTermStore($site, $termStore, $group, $termSet) {    
        $session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
        $termStore = $session.TermStores[$termStore]
        $group = $termStore.Groups[$group]
        $termSet = $group.TermSets[$termSet]
        return $termSet
    if($dev) {
        Write-Host "Running DEV version..."
        $webUrl = "http://Site1"   
        $libraryName = "L1"
        $subjectMatter = "C1"
    } else {
        $webUrl = Read-Host "Enter Site URL" 
        $libraryName = Read-Host "Enter Document Library name"
    $subjectMatter = Read-Host "Enter Subject Matter"
    try {
        $web = Get-SPWeb $webUrl
        $site = $web.Site
        $library = $web.Lists[$libraryName]
        $items = $library.GetItems()
        $subjectMatterTermSet = GetTermStore $site $termStore $group $subjectMatterTermSetName
        $subjectMatterTerm = $subjectMatterTermSet.GetTerms($subjectMatter,$true) | select -First 1
        foreach($item in $items) {
            if([string]::IsNullOrEmpty($item["Subject Matter"])) {     
                #Write-Host "Filename: $filename / Keywords: $keywords / Subject Matter: $subjectMatter / Document Type: $documentType"        
                Write-Host "Updating $($item["ows_FileLeafRef"])..."           
                # Set Subject Matter column
                $subjectMatterField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$item.Fields["Subject Matter"]
                $subjectMatterField.SetFieldValue($item,$subjectMatterTerm)
                # Update Item
                $item.SystemUpdate()
    catch
        $ErrorMessage = $_.Exception.Message
        Write-Host "Something went wrong. Error: $ErrorMessage" -ForegroundColor Red

  • Exchange PowerShell script to get mailbox properties of user from a CSV file

    Hi Team,
    I've a CSV file with alias of numerous users and I want to get their mailbox sizes and other properties. These users are dispersed in various databases of same Exchange organization.
    Need a Powershell Script, Any help?
    Muhammad Nadeem Ahmed Sr System Support Engineer Premier Systems (Pvt) Ltd T. +9221-2429051 Ext-226 F. +9221-2428777 M. +92300-8262627 Web. www.premier.com.pk

    You can use this and modify it to what you need. Output to a file (IE: Export-CSV "path to file"
    If you need more specifics let me know. This one is for one user at a time but can be used to read a CSV file.
    # Notifies the user a remote session needs to be started
    Write-Host "Get a users mailbox size" -fore yellow -back red;
    Write-Host "Please wait while a remote session started" -fore red -back yellow;
    # Import a remote session with exchange
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeservername/Powershell/ -Authentication Kerberos
    Import-PSSession $Session
    Do {
    # Prompts user for a name
    $name = Read-Host "Enter a username"
    # Get the mailbox statistics for that user
    Get-MailboxStatistics $name | fl totalitemsize, storagelimitstatus, totaldeleteditemsize | out-default
    # Give the user a choice to test another or EXIT
    $Output = Read-Host "Press Y to continue or ENTER to exit"
    # Ends the program if the user does not press Y
    Until ($Output -ne "Y")
    HossFly, Exchange Administrator

  • How to set volume using Powershell script?

    I would like to know on how to set volume under Window 7 Home 64 bits system using Powershell script.
    Such as 8000 levels as default
    Does anyone have any suggestions?
    Thanks in advance for any suggestions
    Thanks in advance for any suggestions

    Try this.
    Function Set-SpeakerVolume{
    Param (
    [switch]$min,
    [switch]$max,
    [int]$Percent
    $wshShell = new-object -com wscript.shell
    If ($min){
    1..50 | % {$wshShell.SendKeys([char]174)}
    ElseIf ($max){
    1..50 | % {$wshShell.SendKeys([char]175)}
    elseif($Percent){
    1..50 | % {$wshShell.SendKeys([char]174)}
    1..($Percent/2) |% {$wshShell.SendKeys([char]175)}
    Else{
    $wshShell.SendKeys([char]173)
    This works in Windows 8.1.
    Stolen / Modified from
    http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/28/weekend-scripter-cheesy-script-to-set-speaker-volume.aspx, which took me 20 seconds of (apparently) lucky searching.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Powershell Script to Enable and Disable SharePoint list versioning

    Hi,
    We have a Sharepoint list with a date and time field named 'Today' which we update overnight
    via PowerShell script to give the current date and this recalculates other calculated fields
    in the list.
    All is fine but we have versioning enabled on the list and so we get a new version created everyday.
    Is there a way to disable the versioning prior to running the update and then re-enable
    after?
    This is the script
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    Start-SPAssignment -Global
    $SPWeb = Get-SPWeb "<SharePointSiteUrl>"
    $List = $SPWeb.Lists["ListName"]
    $Items = $List.Items
    foreach ($item in $items)
     $modifiedBy = $item["Editor"]
     $modified = $item["Modified"]
     $item["Today"] = Get-Date
     $item["Editor"] = $modifiedBy
     $item["Modified"] = $modified
     $item.Update()
     $list.Update()
    $SPWeb.Dispose()
    Stop-SPAssignment -Global  

    Hi
    Here is a quick powershell script to iterate a site collection and remove versioning on all list of base-type Document Library. Also the iteration removes all the current versions of list items. Great for freeing up space and also to make publishing sites
    a little more easy to manage content for trusted content approvers!
    Check the below powershell script
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    # Get site
    $site = new-object Microsoft.SharePoint.SPSite("http://YoServer:1002")
    # Iterate all the webs of the site
    foreach ($web in $site.AllWebs)
    # loop through all lists in web
    foreach ($list in $web.Lists)
    # Ensure list is of base Document Library
    if ($list.BaseType -ne "DocumentLibrary")
    # Move on
    continue
    # Loop through each item
    foreach ($item in $list.Items)
    # Get the file
    $file = $item.File
    # Delete all versions
    $file.Versions.DeleteAll()
    # Remove version from the list
    $list.EnableVersioning = $false
    $list.EnableModeration = $false
    # We still want to ensure check out
    $list.ForceCheckout = $true
    $list.Update()
    $web.Dispose();
    $site.Dispose();
    Please mark the Answer and Vote me if you think that it will help you to resolved your issue

  • Not able to configure BDC (Business Data connectivity )service in SharePoint 2012 Using Powershell Script

    HI
    Now there is an  issue while iam running powershell script for BDC service.
    Below is the script i am using to configure BDC service.
    Param(           
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]           
        [string]$ServiceName = $null,
        [Parameter(Mandatory=$true)]           
        [string]$ServiceProxyName = $null,
        [Parameter(Mandatory=$true)]           
        [string]$AppPoolAccount = $null,
        [Parameter(Mandatory=$true)]           
        [string]$AppPoolName = $null,
        [Parameter(Mandatory=$true)]           
        [string]$DatabaseServer = $null,
        [Parameter(Mandatory=$true)]           
        [string]$DatabaseName = $null
    # check to ensure Microsoft.SharePoint.PowerShell is loaded if not using the SharePoint Management Shell
    $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
    if ($snapin -eq $null) {
        Write-Host "Loading SharePoint Powershell Snapin"
        Add-PSSnapin "Microsoft.SharePoint.Powershell"
    Write-Host "Successfully Sharepoint Powershell snapin Loaded"
    Write-Host "Started executing Powershell script for configuring Business Data Connectivity Service in sharepoint farm ..."
    Write-Host -ForegroundColor Yellow "Checking if Application Pool Accounts exists"
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -EA 0
    if($AppPoolAccount -eq $null)
    Write-Host "Please supply the password for the Service Account..."
    $AppPoolCred = Get-Credential $AppPoolAccount
    $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
    Write-Host -ForegroundColor Yellow "Checking wether the Application Pool exists"
    $AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
    if (!$AppPool)
    Write-Host -ForegroundColor Green "Creating Application Pool"
    $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -Verbose
    Write-Host -ForegroundColor Yellow "Checking if BDC Service Application exists"
    $ServiceApplication = Get-SPServiceApplication -Name $ServiceName -ErrorAction SilentlyContinue
    if (!$ServiceApplication)
    Write-Host -ForegroundColor Green "Creating BDC Service Application"
    $ServiceApplication = New-SPBusinessDataCatalogServiceApplication –ApplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer $DatabaseServer –Name $ServiceName
    Write-Host -ForegroundColor Yellow "Starting the BDC Service"
    #$ServiceInstance = Get-SPServiceInstance | Where-Object { $_.TypeName -like "BDC Service*" }
    #Start-SPServiceInstance $ServiceInstance
    Get-SPServiceInstance | where-object {$_.DisplayName -eq $ServiceName} | Start-SPServiceInstance > $null
    Write-Host -ForegroundColor Green "Done - BDC Service is up and running."
    Error i am getting ->
    Started executing Powershell script for configuring Business Data Connectivity S
    ervice in sharepoint farm ...
    Checking if Application Pool Accounts exists
    Checking wether the Application Pool exists
    Creating Application Pool
    VERBOSE: Leaving BeginProcessing Method of New-SPServiceApplicationPool.
    New-SPServiceApplicationPool : The trust relationship between the primary
    domain and the trusted domain failed.
    At C:\SP2013Service\BDC1.ps1:67 char:12
    + $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account
    $AppPoolAcco ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~
        + CategoryInfo          : InvalidData: (Microsoft.Share...ApplicationPool:
       SPCmdletNewIisWebServiceApplicationPool) [New-SPServiceApplicationPool], S 
      ystemException
        + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewIisWe
       bServiceApplicationPool
    VERBOSE: Leaving ProcessRecord Method of New-SPServiceApplicationPool.
    VERBOSE: Leaving EndProcessing Method of New-SPServiceApplicationPool.
    Checking if BDC Service Application exists
    Creating BDC Service Application
    New-SPBusinessDataCatalogServiceApplication : Cannot bind argument to
    parameter 'ApplicationPool' because it is null.
    At C:\SP2013Service\BDC1.ps1:75 char:84
    + ... pplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer
    $DatabaseSer ...
    +                    ~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [New-SPBusinessD...viceApplicat
       ion], ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
       icrosoft.SharePoint.BusinessData.SharedService.SPNewBusinessDataCatalogSer 
      viceApplication

    hi guys,
    same script i have modified with parametes,in below script i have hard corded values for parameters,and it is executing without errors.
    Below is script executing without error->
    Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    #Settings
    $ServiceName = "BDC Service"
    $ServiceProxyName = "BDC Proxy"
    $AppPoolAccount = "DOMAIN\USERNAME"
    $AppPoolName = "BDC SP Ser App Pool"
    $DatabaseServer = "SPSQL"
    $DatabaseName = "SP2013 BDC"
    Write-Host -ForegroundColor Yellow "Checking if Application Pool Accounts exists"
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -EA 0
    if($AppPoolAccount -eq $null)
    Write-Host "Please supply the password for the Service Account..."
    $AppPoolCred = Get-Credential $AppPoolAccount
    $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
    Write-Host -ForegroundColor Yellow "Checking wether the Application Pool exists"
    $AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
    if (!$AppPool)
    Write-Host -ForegroundColor Green "Creating Application Pool"
    $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -Verbose
    Write-Host -ForegroundColor Yellow "Checking if BDC Service Application exists"
    $ServiceApplication = Get-SPServiceApplication -Name $ServiceName -ErrorAction SilentlyContinue
    if (!$ServiceApplication)
    Write-Host -ForegroundColor Green "Creating BDC Service Application"
    $ServiceApplication = New-SPBusinessDataCatalogServiceApplication –ApplicationPool $AppPool –DatabaseName $DatabaseName –DatabaseServer $DatabaseServer –Name $ServiceName
    Write-Host -ForegroundColor Yellow "Starting the BDC Service"
    #$ServiceInstance = Get-SPServiceInstance | Where-Object { $_.TypeName -like "BDC Service*" }
    #Start-SPServiceInstance $ServiceInstance
    Get-SPServiceInstance | where-object {$_.DisplayName -eq $ServiceName} | Start-SPServiceInstance > $null
    Write-Host -ForegroundColor Green "Done - BDC Service is up and running."
    if any body want need more information please can u respond me to
    Email id:[email protected]

  • Powershell script for security groups and users for multiple share folders

    Hi scripting team,
    I need your help with powershell script for the below queries 
    1. List out the security groups for more than one server share path and output it to a file ( csv ) 
    For eg.
    If the are are two share paths 
    \\servername\foldermain\folder1
    \\servername\foldermain\folder2
    So I needs the list of security groups for each share path
    And the output needs to be under each any every path.
    2. Grab the users belongs to main security groups and it nested groups for more than one security group and listed the users under each and every group. No need to display nested groups. Just users belongs to main group and users under nested.
    Your teams help is much appreciated 
    Thank you.
    Thilochana kumararatne

    Hi Braham,
    Thanks for your quick reply.
    Are we able to do this on two stage method
    1. grab the security groups from the share paths
    if can grab the share path from a separate txt file than copying it to the <your path> location
    so i can modify the txt file
    once run the script
    if can the output like below to a CSV file
    \\servername\foldermain\folder1group 1group 2group 3\\servername\foldermain\folder2group 1group 2group 3then i know which groups belongs to which share paththen i can remove the duplicate groups and keep the common groups to grab the users belongs to itso with the second script same as the first copy the security groups to a txt file and the out put as below.what I needs is the users full name and the samaccount name ( user id )group 1user1user2user3
    group 2user1user2user3looking forward your help on thisThank you.Thilo

  • Powershell script assistance - adding another property to existing script

    This is not my script but was written by Richard L. Mueller. It works perfectly for us but I would like to know if the account is enabled or disabled when the output is created. Basically it would output the name, lastlogon and then either enabled or disabled.
    I've attempted to add a new property by adding another " $Searcher.PropertiesToLoad.Add" and "$Result.Properties.Item ".
    It works fine if I add something like "givenName" but I can't find the property name to show if the account is enabled or disabled.
    The entire script is shown below:
    # PSLastLogon.ps1
    # PowerShell script to determine when each user in the domain last
    # logged on.
    # Copyright (c) 2011 Richard L. Mueller
    # Hilltop Lab web site - http://www.rlmueller.net
    # Version 1.0 - March 16, 2011
    # This program queries every Domain Controller in the domain to find the
    # largest (latest) value of the lastLogon attribute for each user. The
    # last logon dates for each user are converted into local time. The
    # times are adjusted for daylight savings time, as presently configured.
    # You have a royalty-free right to use, modify, reproduce, and
    # distribute this script file in any way you find useful, provided that
    # you agree that the copyright owner above has no warranty, obligations,
    # or liability for such use.
    Trap {"Error: $_"; Break;}
    $D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Domain = [ADSI]"LDAP://$D"
    $Searcher = New-Object System.DirectoryServices.DirectorySearcher
    $Searcher.PageSize = 200
    $Searcher.SearchScope = "subtree"
    $Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
    $Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
    $Searcher.PropertiesToLoad.Add("lastLogon") > $Null
    # Create hash table of users and their last logon dates.
    $arrUsers = @{}
    # Enumerate all Domain Controllers.
    ForEach ($DC In $D.DomainControllers)
    $Server = $DC.Name
    $Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    $DN = $Result.Properties.Item("distinguishedName")
    $LL = $Result.Properties.Item("lastLogon")
    If ($LL.Count -eq 0)
    $Last = [DateTime]0
    Else
    $Last = [DateTime]$LL.Item(0)
    If ($Last -eq 0)
    $LastLogon = $Last.AddYears(1600)
    Else
    $LastLogon = $Last.AddYears(1600).ToLocalTime()
    If ($arrUsers.ContainsKey("$DN"))
    If ($LastLogon -gt $arrUsers["$DN"])
    $arrUsers["$DN"] = $LastLogon
    Else
    $arrUsers.Add("$DN", $LastLogon)
    # Output latest last logon date for each user.
    $Users = $arrUsers.Keys
    ForEach ($DN In $Users)
    $Date = $arrUsers["$DN"]
    "$DN;$Date"

    It is part of the userAccountControl attribute. Retrieve that attribute for each user and test if the ADS_UF_ACCOUNTDISABLE bit (2) is set.
    -- Bill Stewart [Bill_Stewart]

  • Is it possible to monitor State change of a .CSV file using powershell scripting ?

    Hi All,
    I just would like to know Is it possible to monitor State change of a .CSV file using powershell scripting ? We have SCOM tool which has that capability but there are some drawbacks in that for which we are not able to utilise that. So i would like
    to know is this possible using powershell.
    So if there is any number above 303 in the .CSV file then i need a email alert / notification for the same.
    Gautam.75801

    Hi Jrv,
    Thank you very much. I modified the above and it worked.
    Import-Csv C:\SCOM_Tasks\GCC2010Capacitymanagement\CapacityMgntData.csv | ?{$_.Mailboxes -gt 303} | Export-csv -path C:\SCOM_Tasks\Mbx_Above303.csv;
    Send-MailMessage -Attachments "C:\SCOM_Tasks\Mbx_Above303.csv" -To “[email protected]" -From “abc@xyz" -SMTPServer [email protected] -Subject “Mailboxex are above 303 in Exchange databases” -Body “Mailboxex are above 303 in Exchange databases" 
    Mailboxex - is the line which i want to monitor if the values there are above 303. And it will extract the lines with all above 303 to another CSV file and 2nd is a mail script to email me the same with the attachment of the 2nd extract.
    Gautam.75801

  • System.Drawing.Bitmap in a scheduled powershell script

    I've written a powershell script to date stamp multipage tiffs, but I check to make sure the file name follows the correct format before doing so. The file name must contain the date, sequence number, and number of pages. The script works fine when run manually,
    but when run from task scheduler it fails to query the number of pages in the TIFF. Any ideas why the .NET features wouldn't work from a powershell script run as a scheduled task?
    I am putting the page number in the variable "count" by doing the following:
     $i=[System.Drawing.Bitmap]::FromFile($file.Fullname);$i.GetFrameCount($i.FrameDimensionsList[0]) 
     $count=$i.GetFrameCount([System.Drawing.Imaging.FrameDimension]::Page)
    FULL SCRIPT FOLLOWS
    #Define the input and output folders and date format
    $Original_TIFFs="C:\scans"
    $Modified_TIFFs=";\\test\Shared\SDS\"
    $date = get-date -Format d
    $datename=Get-Date -format yyyyMMdd
    Set-Location $Original_TIFFs
    #Configure email settings
    $emailFrom = "removed"
    $emailTo = "removed"
    $smtpServer = "removed"
    $body = "Rename scanned claims file to the correct format. This email was sent from: ", $env:computername
    #Define the location of the TIFF command line executable and its parameters
    $200DLL='C:\TiffDLL200Commandline\Cmd200.exe '
    $arg1='"FILE='
    #Modify arg2 to put the output directory in front of the ; if don't want to overwrite current file
    #$arg2=';|OW=Yes|BITS=2|TEXT=2;Received Date: '
    $arg2=$modified_TIFFs
    $arg3=';|BITS=2|TEXT=2;Received Date: '
    $arg4='|TEXTOPS=-5;;10;14;"'
    $files=Get-ChildItem $Original_TIFFs -Filter *.tif
    if ($files -eq $null)
      $subject = "No files to process today, directory empty."
      $smtp = new-object Net.Mail.SmtpClient($smtpServer)
      $body = "No files were processed today. This email was sent from: ", $env:computername
      $smtp.Send($emailFrom, $emailTo, $subject, $body)
    else
    foreach ($file in $files)                                                                  
       #Begin loop to check each file and process
     #Loads subsystems for opening TIFFs and second line puts the number of images into variable
     $i=[System.Drawing.Bitmap]::FromFile($file.Fullname);$i.GetFrameCount($i.FrameDimensionsList[0]) 
     $count=$i.GetFrameCount([System.Drawing.Imaging.FrameDimension]::Page)
     #If statement checks if filename format is correct
     if ($file -match '^\d{8}\d{3}_H_S_\d+_\d{8}[.tif]{4}$')
      $file.name -match '^(?<date1>\d{8})\d{3}_H_S_(?<page_count>\d+)_(?<date2>\d{8})[.tif]{4}$'   #Regex to put tests in $matches to check against
      if (($matches.date1 -eq $datename) -and ($matches.date2 -eq $datename))                      #Check if filename contains correct date
      if ($count -eq $matches.page_count)                                                          #Check if filename
    contains the correct page count
       #insert TIFF modification
        $allargs=$200Dll+$arg1+$file+$arg2+$file+$arg3+$date+$arg4
        cmd /c $allargs
        #cmd /c xcopy $file \\test\shared\SDS                                                   #Deprecated because now having
    TIFF200DLL create a new file rather than overwrite
        $i.Dispose()                                                                  
                #Close file stream so file can be deleted: http://support.microsoft.com/kb/814675
        Remove-Item $file.Name
        #Next section is for a different output directory; Setup a seperate batch file to delete original TIFFs in the middle of the night
        <#
        $allargs="cmd200 "+$arg1+$file+";"+$Modified_TIFFs+";"+$arg2+$date+$arg3
        cmd /c $allargs
        #>
        else                                                                    
                     #else statement to send out error message if the number of pages differs from name
        $subject = "The number of pages in the file ", $file.FullName, "differs from the actual count of ", $count, ". File will not be sent, please correct before tomorrow for processing."
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)
      }  #Close IF/THEN for correct date is in filename
     else
        $subject = "Date portion of filename is incorrect, please fix. File will not be sent to SDS", $file.FullName," ."
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)
     }                                                    #Close IF/THEN for initial filename check
     else
        $subject = "File does not meet proper naming convention and will not be stamped nor sent to SDS", $file.FullName, " ."
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body)
    }                                                     #Close FOR loop
    }                                                     #Close Else for check if FILES=NULL

    You are buikding thisin the ISE?
    You need too add:
    add-type -AssemblyName System.Drawing
    ¯\_(ツ)_/¯

Maybe you are looking for

  • When will Verizon/Mo​torola release a DVR with MORE STORAGE?!?​! This is pathetic

    Just thought I would repost a letter I sent to verizon beggin g for more DVR storage, as 160 GB of  storage is pathetic, and laughable whne I can buy a 2 TB drvie for $100. I realize it is Motorola's fault we are locked to 160 GB at the moment, but V

  • ITunes Store Connection and Error #11333

    I've been getting jerked around about this error as well, and I'm sick of it!!! I can't believe that there is know one available @ Apple with the intelligence and capability to solve this problem. APPLE NEEDS TO START GETTING SOME BAD PRESS & PUBLICI

  • Changing text in a photo?

    Please forgive me if this is in the wrong place, new to PS and this forum. Can anyone tell me if or how you can change text in a photo? I have a picture that I took of a store front with a neon sign. I want to be able to change what the neon sign say

  • Why can't I insert a table in the header?

    This is possible in Word... why not in Pages?

  • Nakisa Org Chart Export Jam

    Hello guys, Am trying to export Nakisa Org Chart (image/PDF/Powerpoint) without success. It gets stuck in below process. I have been trying using IE 8, 9, 11 or even Chrome with Flash Player 14.