Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Make a backup script for backing up email on client's PC

$
0
0

I need to make a complete backup of a user's email on their PC. I will mostly be backing up Outlook.

Microsoft back in the day released "Personal Folders Backup" but it does not work with Outlook 2013.

I was going to deploy a shutdown script to do this but all methods Ive used seem slow.

What suggestions do you guys have for a PowerShell script?


Restore a Database by .bak and .trn using PowerShell

$
0
0

Hello Technet,

I'm a little bit upset because I don't know exactly how to restore the backup I want to.
The main objective is to create it as various as possible (Point in time, NoRecovery, FullRestore, Transaction Restore)

Whenever I try to run the script I receive the following error message:

Restore-SqlDatabase : Failed to resolve the path ‘C:\Program Files\Microsoft SQL 
Server\MSSQL12.SQLEXPRESS\MSSQL\Backup\’ to an object of type 'Microsoft.SqlServer.Management.Smo.Server'. 
Either set your location to the proper context, or use the -Path parameter to specify the location.

But this is the correct path. I've got 2 files here - MSWorks2012backup.bak and MSWorks2012backup.trn

Here's my script

[regex]$rx = "\d+"
$ins = "MyComputerName\SQLEXPRESS"
$backuppath = "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\Backup"
Set-Location "C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\Backup"
#$Log = New-Object ('Microsoft.Sqlserver.Management.Smo.RelocateFile("MyDB_Log","C:\MySSQÖServer\MyDB.ldf")')
$dbs = Get-SqlDatabase -ServerInstance $ins
$tranfile = Get-ChildItem -Filter "*.trn*"
$rs = New-Object('Microsoft.SqlServer.Management.Smo.Restore')
$srv = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $ins
$cmsStore = New-Object ("Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore") $ins
#$RFL = $rs.ReadFileList($srv)
$date = Get-Date
$dbl = @()
$dbl1 = @()
$i = 0
$j = 1
$NA = @()
$count = $srv.Databases.Count
while($i -lt $count)
{
    if($srv.Databases[$i].IsAccessible)
    {
        $db = $srv.Databases[$i]
        $dbname = $db.Name
        $fg = $db.FileGroups
        $fl = $fg.Files
        $dirnm = $fl.FileName
        $filnm = $fl.FileName
        $dfl = $fl | select @{Name="Nr."; Expression={$j}},@{Name="DBName"; Expression={$dbname}}, Name, Size, UsedSpace
        $dbl += $dfl
        $j++
        $fl = $db.LogFiles
        $dirnm = $fl.Filename
        $filnm = $fl.FileName
        $dfl = $fl | select @{Name = "Nr."; Expression={$j}},@{Name="DBName"; Expression={$dbname}}, Name, Size, UsedSpace
        $dbl += $dfl
    }
    else
    {
        $NA += $srv.Databases[$i].Name
        Write-Host "Database $NA is not accessible (offline)." -fore Red
    }
$j++
$i++
}
$dbl | ft -AutoSize
$SI = $dbl[$wo].DBName

$xxx = $true
while($xxx)
{
    $wo = Read-Host "Which database/transactionlog would you like to restore?[digit]"
    if($wo -match $rx)
    {
        $xxx = $false
        if($NA.ToString() -eq "System.Object[]")
        {
            $wo = $wo-1
            $dbl[$wo]
        }
        else
        {
            $wo = $wo-2
            $dbl[$wo]
        }
    }
    else
    {
        $xxx = $true
        Write-Host "Please enter a digit." -fore Red
    }
}
$xx = $true
while($xx)
{
    $pit = Read-Host "Would you like to restore it to point in time?(Y/N)"
    if(($pit -eq "n") -or ($pit -eq "y"))
    {
        $p = $true
        while($p)
        {
            if($pit -eq "y")
            {
                $rec = Read-Host "NoRecovery? Y=True, N=False"
                if($rec -eq "y")
                {
                    Restore-SqlDatabase $dbl[$wo].Name -RestoreAction Log -ToPointInTime $tranfile -Path $backuppath -NoRecovery
                    $p = $false
                    $xx = $false
                }
                elseif($rec -eq "n")
                {
                    Restore-SqlDatabase $dbl[$wo].Name -RestoreAction Log -ToPointInTime -Path $backuppath
                    $xx = $false
                    $p = $false
                }
                else
                {
                    Write-Host "Please enter valid information." -fore Red
                    $p = $true
                    $xx = $false
                }
            }
            elseif($pit -eq "n")
            {
                $rec = Read-Host "NoRecovery Y=True, N=False"
                if($rec -eq "y")
                {
                    Restore-SqlDatabase $dbl[$wo].Name -NoRecovery -Path $backuppath
                    $p = $false
                    $xx = $false
                }
                elseif($rec -eq "n")
                {
                    Restore-SqlDatabase $dbl[$wo].Name -Path $backuppath
                    $p = $false
                    $xx = $false
                }
                else
                {
                    Write-Host "Please enter valid information." -fore Red
                    $p = $true
                }
            }
            else
            {
                Write-Host "Please enter valid information." -fore Red
                $p = $true
            }
        $xx = $false
        }
    }
    else
    {
        Write-Host "Please enter valid information" -fore Red
        $xx = $true
    }
}

Whether point in time recovery works nor norecovery. I really don't know what I need to replace/fix that it works.

Which parameters are crucial to do a Point in Time Recovery, and which files do I need for that?
And also the Restore-SqlDatabase command. What parameters are necessary for my script?

Thanks


Use user input to stop a script

$
0
0

I need a way for a user to stop the current sub-script they're running and go back to the menu script that called the sub-script.

Here's an example:

There's a menu script that shows something like this:

1. Hire

2. Re-Hire

3. Termination

etc

Please choose a number:

If they choose 1, it goes to the hire script which prompts for name, office, title, etc like the following:

write-host "First Name: " -fore yellow -nonewline
$fname = read-host
write-host "Last Name: " -fore yellow -nonewline
$lname = read-host
write-host "Password: " -fore yellow -nonewline
$pass = read-host
write-host "Department: " -fore yellow -nonewline
$dept = read-host
write-host "Title: " -fore yellow -nonewline
$title = read-host
write-host "Manager (username): " -fore yellow -nonewline
$manager = read-host

So then let's say the user is in this script and doesn't want to do that right now and wants to get back to the main menu.  Instead of having to press Ctrl-C and close the script and re-open it, is there a way to catch a certain key press and then exit the sub-script back to the menu?

Could I put something like an if statement on each response that checks whether what the person entered was the ESC key or Ctrl-X or something along those lines?  Like:

write-host "First Name: " -fore yellow -nonewline
$fname = read-host
if ($fname -eq "Ctrl-X") {
.\menu.ps1
}

# I have tried different versions of this, and can't get it to work
...

Or could I wrap the whole thing in some type of while statement that says "while this key hasn't been pressed, do the following" but as soon as that key (ESC) or key combination (Ctrl-X) has been pressed, then go back to the menu?

Hope I'm making this clear...

Adding users to Ad groups based on attributes

$
0
0

I'm trying to build a script where users are added to ad groups based off attributes.

I have the following:

Get-ADUser -filter{department -like “Hydra”} | %{Add-ADGroupMember Hydra-Share$ $_.SamAccountName}

When I run it I receive the following error:

Get-ADUser : Error parsing query: 'department -like “Hydra”' Error Message: 'syntax error' at position: '18'.
At line:1 char:1
+ Get-ADUser -filter{department -like “Hydra”} -Properties department| %{Add-ADGro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.GetADUser

Cannot invoke pipeline because it has been invoked earlier

$
0
0

I a trying to run powershell commands in a loop in code

I am getting this error:

Cannot invoke pipeline because it has been invoked earlier

here is my code:

Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
Dim MyPipeLine As Pipeline = MyRunSpace.CreatePipeline()

Dim MyReturnObjects As Collection(Of PSObject) '= MyPipeLine.Invoke() Collection<PSObject> results = pipeline.Invoke();
Dim MyRunSpaceInvoker As New RunspaceInvoke(MyRunSpace)

For i = 1 To 2 '40
                     strBuilder2 = ""
            strPS2 = ""

            If i = 1 Then
                strPS2 += "$ie = new-object -com " + Chr(34) + "InternetExplorer.Application" + Chr(34) + vbCrLf
            End If

            strPS2 += "$ie.Navigate(" + Chr(34) + strUrl + strURLSuffix + Chr(34) + ")" + vbCrLf 

            strPS2 += "while($ie.busy) { Start-Sleep -Milliseconds 5000 } " + vbCrLf 

            strPS2 += "echo $ie.Document.body.innerHTML | Out-String " + vbCrLf

                 
            'Try
            If i = 1 Then
                MyRunSpace.Open()
            End If
            MyPipeLine.Commands.Clear()
            MyPipeLine.Commands.AddScript(strPS2)
            MyPipeLine.Commands.Add("Out-String")

            MyReturnObjects = MyPipeLine.Invoke()
           
            Try
                If (MyReturnObjects.Count > 0) Then
                    For Each rv In MyReturnObjects
                        strBuilder2 += rv.ToString() + " "
                        'strBuilder.Append(rv.ToString() + " ") ' + "\r\n")
                    Next
                End If
            Catch ex As Exception
                strError += ex.ToString()
            End Try

            strTempPage += strBuilder2 + "<br>************" + strError

        Next
        



y zidell

Help - Rename a Local User Account in Powershell

$
0
0

Hello everyone and thanks for any assistance with this issue,

I've tried to take detailed notes as I work on this. Where I am at there is a setup and initialization process that I am attempting to automate through Powershell. One of the actions is to change an existing user account to a specific nomenclature. For full automation it basically needs to prompt the user for the variables in the beginning of the execution then operate as a fire-and-forget script. I have the variables prompt part working well, but the actual change has been causing some problems. Here is the script and output info I have so far below:

*******************SCRIPT BELOW HERE*******************

# Variables that are needed from the user should all be included here
# in this first section to be prompted for at the beginning of the
# setup process. If the variable is not dynamic to each separate laptop
# and can be defined or pulled without the need for user input then
# please do not include it within this initial variable section!
#
#

$Original_User_Name = Read-Host -Prompt 'What is the original user name?'
$User_Initials = Read-Host -Prompt 'What are the first and last initials to add to the original user name?'
$New_User_Name = $User_Initials + $Original_User_Name


# Variables that are not dynamic, or are able to be pulled dynamically
# WITHOUT user input should be contained in this section below:

$CompStat = Get-WmiObject win32_computersystem
$Localhst = $CompStat.Name

# Display of user entered variables to confirm accuracy before proceeding:

Write-Host "The original user name is $Original_User_Name"
Write-Host "The user's initials are $User_Initials"
Write-Host "The new user name is $New_User_Name"

Write-Host "If these values are correct, press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

# List Item 01 - Rename Local Admin Account


# Attempt #2: In-Progress
$admin= [adsi]("WinNT://"+$Localhst+"/$Original_User_Name,user")
$admin.psbase.Rename('cn=$New_User_Name')

# Attempt #1: Failed
# $admin=[adsi]"WinNT://hostname/$Original_User_Name,user"
# $admin.psbase.rename("$New_User_Name")



# This will keep the window open so admins know the script completed or
# see if any errors were encountered during the process in the event the
# registry settings were not already configured for -noexit

Read-Host -Prompt 'Press Enter to exit'

*******************END SCRIPT*******************

This is the error I am getting. I have removed sensitive info so the username value and file path are not there:


What is the original user name?: REDACTED
What are the first and last initials to add to the original user name?: REDACTED
The original user name is REDACTED
The user's initials are REDACTED
The new user name is REDACTED
If these values are correct, Press any key to continue ...
Exception calling "Rename" with "1" argument(s): "Access is denied. (Exception
from HRESULT: 0x80070005 (E_ACCESSDENIED))"
At REDACTED:36 char:21
+ $admin.psbase.Rename <<<< ('cn=$New_User_Name')
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Press Enter to exit:


I have tried a lot of different syntax to try and get the actual change after psbase.Rename to work correctly, but every one yields this same error.

Here's a list of most of the syntax I have tried:

$admin.psbase.rename('cn=$New_User_Name')
$admin.psbase.rename(cn=$New_User_Name)
$admin.psbase.rename(cn='$New_User_Name')
$admin.psbase.rename("cn=$New_User_Name")
$admin.psbase.rename(cn=$New_User_Name)
$admin.psbase.rename(cn="$New_User_Name")
$admin.psbase.rename('$New_User_Name')
$admin.psbase.rename($New_User_Name)
$admin.psbase.rename('$New_User_Name')
$admin.psbase.rename("$New_User_Name")
$admin.psbase.rename($New_User_Name)

I have also used some write-host lines to check that my variables were correct along the way and found no issues. I am brand new to this and would greatly appreciate any input that would help me get this working. I have gotten this far off of simply reading about how to change a username through powershell. I have no formal training, just my brain, analytical skills, and a few years hacking at video game dev commands.

The error output has me wondering if there is some type of additional authentication needed before I would be able to actually change the user name on the account. I am logged in on a local administrator account and am trying to change a local user account who is also a local admin. No interfacing with Active Directory is needed unless I am missing something here. Please let me know and thanks again for any assistance.

Last Access Time of a Group of Folders

$
0
0

Hi,

I am running below command to get the last access time of folders:

Get-ChildItem\\PATH\DIR | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-180)}

There are some folders whose access time stamp is being altered by SharePoint Crawler Service and I want to exclude it from my result.

Can someone please suggest a script here to accomplish that ?

Thanks.


Thanks, Yeleshwar

Script to clear Internet cache remotely

$
0
0

I am looking for a way to clear "IE cache" for all the user profile folders remotely for list of Windows 2012 servers. Can someone help?




Powershell 4 transcription broken

$
0
0

Hi, after installing KB2919355 for Windows Server 2012R2 (or Windows 8.1) the transcription functionality of Powershell seems to be broken.

Input:

PS C:\Windows\system32> start-transcript c:\test.log
Transcript started, output file is c:\test.log
PS C:\Windows\system32> write-host "testing write-host"
testing write-host
PS C:\Windows\system32> "testing out-host" | out-host
testing out-host
PS C:\Windows\system32> stop-transcript
Transcript stopped, output file is C:\test.log
PS C:\Windows\system32>

Output:

**********************
Windows PowerShell transcript start
Start time: 20150428205107
Username: HHO\Henk
RunAs User: HHO\Henk
Machine: HHO (Microsoft Windows NT 6.3.9600.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 4508
**********************
Transcript started, output file is c:\test.log

PS C:\Windows\system32> write-host "testing write-host"

PS C:\Windows\system32> "testing out-host" | out-host
testing out-host

PS C:\Windows\system32> stop-transcript
**********************
Windows PowerShell transcript end
End time: 20150428205143
**********************
It was already asked in this thread: https://social.technet.microsoft.com/Forums/en-US/cecc4f32-28c8-4bdc-be63-49ce3d396625/powershell-4-starttranscript-does-not-log-writehost?forum=winserverpowershell

But the last response from microsoft is that they are working on it, in februari, and it has been very silent since then.

I'd like to see a response from MSFT about this!


Kind Regards, Henk Hofs | http://www.IThastobecool.com

PS script to remove a section from an .xml file

$
0
0

I am trying to remove a block of lines from a text file whenever it changes. The file has start and end tags and I'd like to remove both tags and everything in between. For example, the start and end tags "TrashTag" below and the three lines should be removed if they exist in the file.

< TrashTag >
this goes
remove this
and this
< /TrashTag >

Get-ADUser format date properties

$
0
0

For the correct importation into a SQL table I need the date portion of the datetime to be in the yyyy/MM/dd format instead of dd/MM/yyyy for the Created property

Get-ADUser - filter * Created, Department | Select-Object Name, Created, Department ! Export-CSV c:\temp\a.txt
Can this be done for the one liner above?

Automate/schedules Backup for Windows Server 2012R2 using Powershell script

$
0
0

i want to learn how to automate repetitive task like backing up files and restarting the machine for updates using windows powershell

please guide me through this as i am a beginner in this industry & not too familiar with PowerShell commands, 

also suggest me other ways to do scheduled backup for windows server 2012


VirtualMachineManager: set ipv4address and DNS Settings

$
0
0

hi

How can I define an ipv4address and the DNS Settings?

$template = Get-SCVMTemplate -All | where { $_.Name -eq "$TemplateName" }
$virtualMachineConfiguration = New-SCVMConfiguration -VMTemplate $template -Name "$ServerName"
Write-Output $virtualMachineConfiguration
$vmHost = Get-SCVMHost -ID "a86731ad-50e6-4e61-b7e5-263157b940b6"
Set-SCVMConfiguration -VMConfiguration $virtualMachineConfiguration -VMHost $vmHost
Update-SCVMConfiguration -VMConfiguration $virtualMachineConfiguration
Set-SCVMConfiguration -VMConfiguration $virtualMachineConfiguration -VMLocation $VMLocPath -PinVMLocation $true

$AllNICConfigurations = Get-SCVirtualNetworkAdapterConfiguration -VMConfiguration $virtualMachineConfiguration
$AllNICConfigurations | Set-SCVirtualNetworkAdapterConfiguration -IPv4PAAddress $IPAddress

many thanks

Miller


formating output

$
0
0

$data= Get-WMIObject  -ComputerName $computers Win32_LogicalDisk `
| select DriveType, VolumeName, Name, {($_.size/1gb)},{($_.freespace/1gb)},{($_.freespace/$_.size*100)}`

Write-Output $data

gets me 

DriveType                  : 3
VolumeName                 : 
Name                       : C:
($_.size/1gb)              : 97.6533164978027
($_.freespace/1gb)         : 73.4033164978027
($_.freespace/$_.size*100) : 75.1672540475923

DriveType                  : 5
VolumeName                 : SQLServer
Name                       : D:
($_.size/1gb)              : 3.63286781311035
($_.freespace/1gb)         : 0
($_.freespace/$_.size*100) : 0

DriveType                  : 3
VolumeName                 : sql
Name                       : E:
($_.size/1gb)              : 299.997066497803
($_.freespace/1gb)         : 299.408504486084
($_.freespace/$_.size*100) : 99.803810744355

how can i get it so this outputs in a comma delimmeted row? 

Exporting ADGroupMember results to CSV

$
0
0

Hi,

I am currenlty running the following script to get a list of all members within a list of AD Security Groups

$Groups = Get-ADGroup -Filter {name -like "FIL_*"}

Foreach ($Group in $Groups)
{
Write-output $Group.name
Get-ADGroup -Identity $Group | Get-ADGroupmember | format-list name

}

I want to export the results to excel with the Security Group names as the headers and then going down each column would be the members of the group.

Everything i try either leaves the output to excel as a blank worksheet or has non meaning full information in the worksheet.

Could you please help me with this?



How can I Do... Update Extension attribute

$
0
0

Hi, I have a Script to update some values in Active Directory from a CSV file, and works fine...

Import-Module ActiveDirectory

Import-CSV C:\Test\Users.csv  |

ForEach-Object {
         $record = $_
         $s = @{}
            if ($record.empnum) {$s["EmployeeID"] = $record.empnum }
            if ($record.Phone) {$s["OfficePhone"] = $record.phone }
     ... etc...

     Get-ADUser -filter "Name -eq `"$($_.nameusr)`"" | Set-ADUser @s

}

Now the challenge is update some data to "extension attribute", so I try with some like:

     if ($record.usrID) {$s["extensionAttribute5"] = $record.usrID }

But i have this error:

Set-ADUser : A parameter cannot be found that matches parameter name 'extensionAttribute5'

Any suggestions on how to do this?

Tks

Powershell Error --- This command cannot be run due to the error: Only part of a ReadProcessMemory or WriteProcessMemory request was completed

$
0
0

Hi expert, 

I am running a powershell script which runs the other powershell Script with other user who has admin rights on machine. 

This script runs on few machines and on machines is not running. It gives following error. 

start-process : This command cannot be run due to the error: Only part of a ReadProcessMemory or WriteProcessMemory request was completed

Please give some suggestion ...... 

AD physicalDeliveryOfficeName If statement

$
0
0

Guys.

I am having brain freeze today. I have constructed the script below. I am looking to get all users in an OU and if their physicalDeliveryOfficeName AD attribute match what is in my IF statement then do something.

The issue im having is it never matches the location and skips to site unknown. I have done this kind of thing before and im having a serious off day as i cant quite remember what im missing.

------

$OUSelected = "OU NAME HERE"
$Location = Get-qaduser -SizeLimit 0 -SearchRoot $OUSelected | Select-Object physicalDeliveryOfficeName `
| ForEach-Object {

if ($Location -eq "London")
{
       Write-Host "1";
}
elseif ($Location -eq "Milan")
{
       Write-Host "2";
}
elseif ($Location -eq "Padova")
{
       Write-Host "3";
}
elseif ($Location -eq "Geneva")
{
       Write-Host "4";
}
else
{
       Write-Host "No site";
}

}

How to create NTDS Active Directory Connection Objects with Powershell

$
0
0

Hello there

I need to create 240 replication connectors (NTDS Connection Objects in ADS&S) for the new Windows Server 2008 DCs I am going to deploy.

I am searching a fast scriptable way to create with Powershell modules for AD. I can't find a way to do it.

Can anyone please help me out?

Thank you so much in advance

remove EUM from all exchange 2007 users

$
0
0

Hello

I need to remove the EUM entry from all users.

I don't have an existing email address policy.

thank you

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>