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

Similar Messages

  • 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.
    ¯\_(ツ)_/¯

  • Powershell Scripting Help

    So, I am building somepowershell scripts for better management of the windows side of our domain
    I had a major issue that I want to try, and I was wondering if someone could help me out here:
    I want to use powershell to get all users in Active Directoy, and I want the script to list the OU that the users happen to be in.
    For Example:
    Domain.net
    Admin 1, OU: Admins
    Admin 2, OU: Admins
    User 1, OU: Users
    etc, etc
    Is this at all possible? I have tried combinging various scripts and variables I have found through online resources, but the outcome has been rather... well, a failure to be honest.
    Any help would be greatly appreciated.
    Thanks in advance.

    I have a long ramble:http://community.spiceworks.com/topic/1048057-outlook-calendar-disappeared-overnight-office-updates-maybe-coincidence
    where I am trying to work out what happened and then saw this:http://answers.microsoft.com/en-us/office/forum/office_365hp-outlook/outlook-rss-feed-problem-after-last-office-365/073b5c31-3015-4386-a6d8-36e7747d92f0
    which leads me to believe it isn't me going made, trigger finger...., but a borked Office update.

  • Powershell script for Use this termset for site navigation in tem store management tool in central admin

    can anyone pls point out whats the power shell script for "use this  termset for site navigation" in the termstore management tool in my central  admin';s manage serv appln-->managed metadata serv appln ->term styore mgmnt tool
    i would like to check this "checked" through powershell script
    help is appreciated!

    Hi,
    To check if the term set has been set to be used for site navigation, we need to check the
    NavigationTermSet.IsNavigationTermSet property for the term set.
    Here is the code example for using PowerShell to get the setting:
    $site=Get-SPSite "your site collection URL";
    $session = Get-SPTaxonomySession -Site "your site collection URL ";
    $termStore = $session.TermStores["Managed Metadata Service"];
    $Group = $termStore.Groups[“Group Name”];
    $TermSet = $Group.TermSets[“Term Set Name”];
    $navTermSet = [Microsoft.SharePoint.Publishing.Navigation.NavigationTermSet]::GetAsResolvedByWeb($termset, $site.RootWeb, "GlobalNavigationTaxonomyProvider");
    write-host $navTermSet.IsNavigationTermSet
    Best regards.
    Thanks
    Victoria Xia
    TechNet Community Support

  • 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

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

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

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

  • Powershell - Need help combining multiple commands (?) into one script

    Scenario:
    When a user is terminated from our company, I run these scripts separately:
    1. I use the script below in Windows Powershell ISE to launch an entry box so I can enter in the username@domain and get a list of distribution groups the termed employee currently manage export to a CSV file on my desktop:
    Add-PSSnapin quest.activeroles.admanagement
    $USerID = Read-host "Enter in Username@domain. Example: [email protected]"
    connect-QADService -service blah.dc1.cba.corp -UseGlobalCatalog
    get-qadgroup -ManagedBy $UserID -Verbose | select Name,Type,DN | export-csv -
    NoTypeInformation "$home\desktop\$UserID.csv" -Verbose -Force
    2. I launch Powershell as an Administrator and run the following to activate Exchange Management in Powershell and to give me access to the entire forest of accounts:
    Add-PSSnapin -name "Microsoft.Exchange.Management.PowerShell.E2010"
    Set-AdServerSettings -ViewEntireForest $true
    3. Next, I run this script to remove the former owner's write permissions from the list of distribution lists they managed in the above CSV file:
    import-csv -Path "<PATH>" | Foreach-Object {Remove-ADPermission -Identity $_.Name -
    User '<domain\username>' -AccessRights WriteProperty -Properties “Member” -
    Confirm:$false}
    4. I run this script to show the new owner of the DLs, allow DL management via Webmail and add info in the Notes section on the DLs:
    import-csv -Path "<PATH>" | Foreach-Object {set-Group -Identity $_.Name -ManagedBy
    "<domain\username>" –Notes “<Enter Here>”}
    5. I run this script to allow management via Outlook and to automatically check the box in Active Directory "Manager can update membership list" under the Managed By tab within the Group's Properties:
    import-csv -Path "<PATH>" | Foreach-Object {Add-ADPermission -Identity $_.Name -User
    ‘<domain\username’ -AccessRights WriteProperty -Properties “Member”}
    Is there a way I can combine this into one Powershell script or two, at the most instead of having to copy and paste 6 different times and use two programs (Powershell and Powershell ISE)? 

    Rhys, again, thanks to your script, I was able to add even more to it to run nicely in PowerShell ISE (running as an Administrator):
    The following happens in the script below in this order:
    1. The script allows searching across multiple e-mail domains that we manage in Exchange
    2. It prompts for entry of the old owner's ID, the new owner's ID and notes that I want to add to the DLs.
    3. It exports a copy of lists owned by the old owner to a CSV file on my desktop.
    4. Powershell pauses and allows me to modify the old owner's.CSV file so I can remove any lists that should not be transferred, save the changes to the CSV file and click continue in Powershell ISE. If all lists should be transferred to the new owner, I
    would simply not edit the CSV export and click OK in Powershell ISE.
    5. Powershell ISE updates the DLs from the CSV export using the information I entered in the entry boxes.
    6. Powershell sleeps for about 1 minute after updating the DLs to allow Active Directory to register the changes. Then, Powershell ISE exports a copy of the lists transferred to the new owner to a <newownerID>.csv file on my desktop. This allows me
    to compare the CSV files (which should have the same exact lists on them) and make sure all of the lists were successfully transferred.
    7. If the lists are not the same because Active Directory didn't update in time while the file csv export was running for the new owner, I can run the script again with the exception of using the newownerID for the entry boxes in Step 2 (Notes don't matter
    as we won't execute any additional steps after capturing the updated export). You would simply select Cancel during the pause window that comes after the export completes to prevent the script from continuing a second time and overwriting your previous entries.
    8. You can now compare the updated newowner.csv to the oldowner.csv file on your desktop. 
    Add-PSSnapin -name "Microsoft.Exchange.Management.PowerShell.E2010"
    Add-PSSnapin quest.activeroles.admanagement
    Set-AdServerSettings -ViewEntireForest $true
    connect-QADService -service xyz-fakeserver.corp -UseGlobalCatalog
    Do {
       $FormerOwner = Read-host "Enter in former DL owner as Username@domain."
       $UserID = Read-host "Enter in new DL owner as Username@domain."
       $Notes = Read-host "Enter in Notes for DL"
       Try {
          get-qadgroup -ManagedBy $FormerOwner -Verbose -ErrorAction Stop | select Name | export-csv -NoTypeInformation "$home\desktop\$FormerOwner.csv" -Verbose -Force
    Read-Host 'Edit <FormerOwner>.CSV file on desktop to remove groups that should stay with current owner, save changes and press Enter or click OK to continue script. If all groups need to be transferred to new owner, do not modify CSV file and press Enter
    or click OK to continue.' 
    import-csv -Path "$home\desktop\$FormerOwner.csv"
    $UserList = import-csv "$home\desktop\$FormerOwner.csv"
    $Userlist | Foreach-Object {
             Remove-ADPermission -Identity $_.Name -User $FormerOwner -AccessRights WriteProperty -Properties “Member” -Confirm:$false
             set-Group -Identity $_.Name -ManagedBy $UserID –Notes $Notes
             Add-ADPermission -Identity $_.Name -User $UserID -AccessRights WriteProperty -Properties “Member”
    Start-Sleep -s 60
    get-qadgroup -ManagedBy $UserID -Verbose -ErrorAction Stop | select Name | export-csv -NoTypeInformation "$home\desktop\$UserID.csv" -Verbose -Force
          $Flag = $True
       } Catch {
          Write-Host "Invalid username or user not found, please try again"
    } While (!$Flag)

  • Using Echo Command in PowerShell Script for Configuration Item

    Hello All,
    Before you tell me to post my PowerShell question to the PowerShell Forum, please know that the PowerShell portion of my task works just fine. It is the SCCM portion of my task that keeps failing, so that is why I am here. To give some background...
    There are two servers in our SCCM test environment. Both the SCCM server and SQL DB server are 2012, patched and updated.
    Test servers in my Device Collection being used for running Baselines and Reports against are 2008R2 and 2012, patched and updated.
    I have created a Configuration Item that checks to see if the FTP Server Role Feature has been installed on a 2008 or 2012 server. To do the check, I am using the following PowerShell script:
    (get-windowsfeature -Name Web-Ftp-Server).Installed
    When I log into my 2008R2 and 2012 test servers, and run this command directly on the server, it will return a "True" if the FTP Server Role Feature is installed on either server, and a "False" if it is not installed. Basically,
    it works as advertised.
    When I setup my Configuration Item and then deploy my Baseline, or run a report against my device collection of test servers, SCCM will return a correct response (True or False) for the 2012 test server, but throws the following error for the 2008R2
    server:
    0x87df00329 application requirement evaluation or detection failed
    Google searches for this have not been very helpful.
    Now, when I created the Configuration Item and referenced PowerShell, the configuration screen has the following note:
    "Specify the script to find and return the value to be assessed for compliance on client devices. Use the echo command to return the script value to Configuration Manager."
    Since I did not include an echo command in my PowerShell script above, I figured that was my problem, so I did the following:
    Logging onto both of my test servers (2008R2 & 2012) I was able to successfully run the following PowerShell commands and get the expected responses of True or False:
    (get-windowsfeature -Name Web-Ftp-Server).Installed | echo
    (get-windowsfeature -Name Web-Ftp-Server).Installed | write-output (http://technet.microsoft.com/en-us/library/hh849921.aspx)
    (get-windowsfeature -Name Web-Ftp-Server).Installed | write-host (http://technet.microsoft.com/en-us/library/ee177031.aspx)
    However, when I use any of these PowerShell commands in my Configuration Item, NEITHER of my test servers returns a response to the SCCM server.
    When I check the report, both servers show as "Unknown" and when I click on the number 2 (as in 2 servers unknown), the following report page (List of unknown assets for a configuration baseline) has absolutely no data/information at all.
    So...I am at a loss.
    SCCM tells me to use an echo command to return a script value to Configuration Manager. The PowerShell scripts above, with the various echo related commands, work just fine on the servers themselves, but they return no information when run via SCCM.
    What am I missing?
    Any help will be appreciated.
    Thanks in advance for your time.

    Sorry for my ignorance, but I don't understand. (I forgot to mention that I am new at both PowerShell and SCCM.)
    After I change the PowerShell script to add the echo/write-output/write-host cmdlet, I open the ConFig Item and "Clear" the PowerShell script and then re-add it. When I do that, it correctly shows the change in the ConFig Item.
    Next I open the Baseline, then open the ConFig Item within the Baseline to make sure the change is reflected there as well, which it is.
    I then deploy the Baseline to my Device Collection. After that, I run a report against the Baseline and Device Collection and it returns the "Unknown" result.
    If I open the PowerShell script and remove the echo/write-output/write-host cmdlet, then go through the rest of the process of updating and reporting, the result it returns changes, showing one server in compliance and the other server out of compliance,
    which leads me to think that all changes have taken correctly.
    Does that sound right? If I manually deploy the Baseline, is that the same as the client retrieving policies from the management point?
    Sorry to be so thick but I'm learning as I go.
    Thanks again for your help.

  • Powershell script - how to read a registry hive and store the value in text file and then again read the text file to write the values back in registry

    Hi All,
    powershell script Method required to read a value from registry and then taking the backup of that values in some text file.
    For example the hive is
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path
    and under path i need to take back up  of values in some text file and then put some value in the registry after back is taken in text file.
    Also how to read the text file values so that we can again write to registry hive  back from the back up text file.
    Your help is much appreciated.
    Umeed4u

    I think you need to read this first:
    http://social.technet.microsoft.com/Forums/scriptcenter/en-US/a0def745-4831-4de0-a040-63b63e7be7ae/posting-guidelines?forum=ITCG
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • SharePoint PowerShell script to open Excel.Application on Windows server 2008 R2

    Hi
    I am building a PowerShell script to open an Excel file store on SharePoint document library.  Sound simple enough but I just couldn't get over an error and hopefully someone can help give an answer here.
    I have found many sample codes to use.  All of the sample codes show that a new object must be created for Excel application
    like ($Excel = New-Object -comobject Excel.Application) before that excel file can be read.
    When I run this comand on a SharePoint server (Windows 2008 R2) either inside the script or by itself I keep getting the following error:
     New-Object : Cannot load COM type Excel.Application.
    + $excel = New-Object <<<<  -Com Excel.Application
        + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    For the test,  I ran this comand on a Windows 7 with MS Office applications installed,  then it ran fine.
    Is that because I don't have Office application (Excel) installed on the server to run this or some services need to be turned on?
    From the sample codes, look like I should be able to run it on the Server with SharePoint installed.
    Thanks for any advice or solution to resolve my issue.
    Swanl

    So I'm assuming this won't return anything either?
    Get-WMIObject Win32_ClassicCOMClassSetting | ? {$_.VersionIndependentProgId -like 'excel.application'}
    You need Office/Excel installed on the server because you're accessing those .DLLs for the automation functionality, but depending on what you're trying to do you may be able to use one of the office viewers:
    http://www.microsoft.com/en-us/download/details.aspx?id=10 although I'm not sure how much of the com (if any) is exposed in a viewer install.  if Office is not possible due to
    budget reasons, I believe there are several 3rd party providers who can produce a com object that will handle Excel formats.

Maybe you are looking for