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

How can I combine Add-DnsServerResourceRecordA & Add-DnsServerResourceRecordPTR cmdlets to automate creating DNS records?

$
0
0

PowerShell gurus,

We are running Windows Server 2012 R2 with PowerShell v4.0 and want to take advantage of the new Add-DnsServerResourceRecordA and  Add-DnsServerResourceRecordPTR cmdlets (and remove-dnsserverresourcerecord) to automate as much as possible the creation/deletion of statically configured DNS records.

Question: how can I combine these two cmdlets to run to create the DNS 'A' and DNS 'PTR' records in one long cmdlet?  How would we make it so we can run both of these below together as one cmdlet?

Add-DnsServerResourceRecordA-Name "hostname123"-ZoneName "contoso.com"-AllowUpdateAny -IPv4Address"192.168.0.123" -TimeToLive 01:00:00

Add-DnsServerResourceRecordPtr -Name "123" -ZoneName "0.168.192.in-addr.arpa" -AllowUpdateAny -TimeToLive 01:00:00 -AgeRecord -PtrDomainName"hostname123.contoso.com"  

As we develop our competence with powershell, we would like to make it so we can use (get-content) to import DNS entries from a .csv file then as much as possible automate the creation of DNS 'A' and 'PTR' records.  How can we do this?

Thank you for your insight and ideas!

Cheers!


Matt


Application.Outlook error in Powershell

$
0
0

Hi All,

I am getting an error when running this:

$var = New-Object -ComObject Application.Outlook

Error:

New-Object : Retrieving the COM class factory for component with CLSID {00000000-0000-0000-0000-000000000000} failed 
due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
At line:1 char:8+ $var = New-Object -ComObject Application.Outlook+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMException+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand

I am running Powershell 3.0, Office 2013 x64, on Win 8 x64.

I tried both combinations of running PS and Outlook as Local and Admin, but got error in both.

I am running an x64 environment for PS.

Do i need to have x86 Outlook for this? or Do i need to install any cmdlets for outlook access from PS??

Thanks in advance! :)

Search for records in the event viewer after the last run (not the entire event log), remove duplicate - Output Logon type for a specific OU users

$
0
0

Hi,

The following code works perfectly for me and give me a list of users for a specific OU and their respective logon types :-

$logFile = 'c:\test\test.txt'

$_myOU = "OU=ABC,dc=contosso,DC=com"
# LogonType as per technet
$_logontype = @{
    2 = "Interactive" 
    3 = "Network"
    4 = "Batch"
    5 = "Service"
    7 = "Unlock"
    8 = "NetworkCleartext"
    9 = "NewCredentials"
    10 = "RemoteInteractive"
    11 = "CachedInteractive"
}
Get-WinEvent -FilterXml "<QueryList><Query Id=""0"" Path=""Security""><Select Path=""Security"">*[System[(EventID=4624)]]</Select><Suppress Path=""Security"">*[EventData[Data[@Name=""SubjectLogonId""]=""0x0"" or Data[@Name=""TargetDomainName""]=""NT AUTHORITY"" or Data[@Name=""TargetDomainName""]=""Window Manager""]]</Suppress></Query></QueryList>" -ComputerName"XYZ" | ForEach-Object {
    #TargetUserSid
    $_cur_OU = ([ADSI]"LDAP://<SID=$(($_.Properties[4]).Value.Value)>").distinguishedName
    If ( $_cur_OU -like "*$_myOU" ) {
        $_cur_OU
        #LogonType
        $_logontype[ [int] $_.Properties[8].Value ]
#Time-created
$_.TimeCreated
    $_.Properties[18].Value
    } 
} >> $logFile


I am able to pipe the results to a file however, I would like to convert it to CSV/HTML When i try "convertto-HTML" function it converts certain values . Also,

a) I would like to remove duplicate entries when the script runs only for that execution. 

b) When the script is run, we may be able to search for records after the last run and not search in the same records that we have looked into before.

PLEASE HELP ! 

How does .NET refer to "by reference" in method calls?

$
0
0

Consider the following code that modifies some of the elements of array $a

$a = 1,2,4,5,3,6
[array]::sort($a)

What sort of lingo describes the arguments to a method where the method may modify the object passed to it?

I'd say "by reference" but I don't see that phrase used in the .NET MSDN documentation.

Question on accessing UI after starting PSJob

$
0
0

Hi,

I am starting job to do various things like restart services. When you start a job, why can you not then within its curly braces write-host or access the UI controls, like you can just before you enter the start-job? See below:

Start-Job -ScriptBlock {

Write-Host "Start Job"
$ButtonTest.background = "Orange"

Is it possible within the job to access these controls? Also why would you need to use -ScriptBlock with start-job?

Thanks a lot!

Powershell script to remove Windows Sidebar folder and its contents from Windows 7 machines if present

$
0
0

I am very new to powershell, I just need a method to remove the Windows Sidebar from over 100 Windows 7 machines.  I am using domain admin privaleges. This is what I have so far:

_____________

# List of Computers

$name = Get-ADComputer -Filter * -Properties * | foreach-object {$_.name}

# folder to delete

$Cfolder = Get-ChildItem "C\Program Files\Windows Sidebar\" -Force -Recurse

$name Remove-Item $Cfolder -Force -Recurse

________________

With variations of the above I get Acces to the path is denied.

Even trying to log in locally and use:

Remove-Item -Path "C\Program files\Windows Sidebar\" -Force -Recurse

I get access to the path is denied. Using the Set-Owner command does not work.

Search for records in the event viewer after the last run (not the entire event log) - Output Logon type for a specific OU users

$
0
0

Hi,

The following code works perfectly for me and give me a list of users for a specific OU and their respective logon types :-

$logFile = 'c:\test\test.txt'

$_myOU = "OU=ABC,dc=contosso,DC=com"
# LogonType as per technet
$_logontype = @{
    2 = "Interactive" 
    3 = "Network"
    4 = "Batch"
    5 = "Service"
    7 = "Unlock"
    8 = "NetworkCleartext"
    9 = "NewCredentials"
    10 = "RemoteInteractive"
    11 = "CachedInteractive"
}
Get-WinEvent -FilterXml "<QueryList><Query Id=""0"" Path=""Security""><Select Path=""Security"">*[System[(EventID=4624)]]</Select><Suppress Path=""Security"">*[EventData[Data[@Name=""SubjectLogonId""]=""0x0"" or Data[@Name=""TargetDomainName""]=""NT AUTHORITY"" or Data[@Name=""TargetDomainName""]=""Window Manager""]]</Suppress></Query></QueryList>" -ComputerName"XYZ" | ForEach-Object {
    #TargetUserSid
    $_cur_OU = ([ADSI]"LDAP://<SID=$(($_.Properties[4]).Value.Value)>").distinguishedName
    If ( $_cur_OU -like "*$_myOU" ) {
        $_cur_OU
        #LogonType
        $_logontype[ [int] $_.Properties[8].Value ]
#Time-created
$_.TimeCreated
    $_.Properties[18].Value
    } 
} >> $logFile



I am able to pipe the results to a file however, I would like to convert it to CSV./HTML When i try "convertto-HTML" function it converts certain values . Also,

a) I would like to remove duplicate entries when the script runs only for that execution. 

b) When the script is run, we may be able to search for records after the last run and not search in the same records that we have looked into before.

PLEASE HELP ! 


Piping a csv to the Set-Mailbox cmdlet

$
0
0

Hi,

I have a CSV file populated with a list of users SPN's in the following format:

User

user1@domain.local

user2@domain.local

I am getting an odd error when I run the following:

$users = c:\scripts\userlist.csv

foreach ($user in $users) {Set-Mailbox $user -UseDatabaseQuotaDefaults $false -ProhibitSendReceiveQuota
1 -IssueWarningQuota 1 -ProhibitSendQuota 1 -hiddenfromaddresslistsenabled $true}

Cannot process argument transformation on parameter 'Identity'. Cannot convert the "@{User=user1@domain.local}" value of type "Deserialized.System.Management.Automation.PSCustomObject" to type "Microsoft.Exchange.Configuration.Tasks.MailboxId
Parameter".



When I do a foreach ($user in $users) {write-host $user} I get the contents of the CSV but with "@{user=" prepended to every entry.

What am I doing wrong? Any help much appreciated.


Ouputing ForEach loop to a $richTextBox

$
0
0

Hi

I'm a PowerShell newbie and need some help.

I'm in the middle of convert a nice PowerShell script that I found on the NET which 'finds lockout out locations in AD'.  I have been tasked to make a GUI using PowerShell studio 2012 to give to our Helpdesk Dept.

http://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content

I'm trying to display the below output to a $richTextBox, but can't get it to work.


Foreach($Event in $LockedOutEvents) 
       {             
           If($Event | Where {$_.Properties[2].value -match $UserInfo.SID.Value}) 
           {  
		$Event | Select-Object -Property @( 
              	@{Label = 'User';               Expression = {$_.Properties[0].Value}} 
                @{Label = 'DomainController';   Expression = {$_.MachineName}} 
                @{Label = 'EventId';            Expression = {$_.Id}} 
                @{Label = 'LockedOutTimeStamp'; Expression = {$_.TimeCreated}} 
                @{Label = 'Message';            Expression = {$_.Message -split "`r" | Select -First 1}} 
                @{Label = 'LockedOutLocation';  Expression = {$_.Properties[1].Value}} 
              ) 
            }#end ifevent 
       }#end foreach lockedout event 

This is what the output looks like when I run it via the PowerShell console.  It checks the event viewer on the DC and reports back each time a user has been locked out.

User               : test

DomainController   : WIN-HVUFA7OGP6C.bscull.local

EventId            : 4740

LockedOutTimeStamp : 03/09/2014 15:05:45

Message            : A user account was locked out.

LockedOutLocation  : WIN8

 

User               : test

DomainController   : WIN-HVUFA7OGP6C.bscull.local

EventId            : 4740

LockedOutTimeStamp : 03/09/2014 14:52:39

Message            : A user account was locked out.

LockedOutLocation  : WIN8

 

User               : test

DomainController   : WIN-HVUFA7OGP6C.bscull.local

EventId            : 4740

LockedOutTimeStamp : 01/09/2014 22:18:19

Message            : A user account was locked out.

LockedOutLocation  : WIN8

Hope you can help

Thanks!!!

Exception calling Open - Type mismatch

$
0
0

Hi there,

What are the common problems when we get this error message ?

Exception calling "Open" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

Part of my source code : 

$application = New-Object -ComObject word.application
$application.Visible = $false
$binding = "System.Reflection.BindingFlags" -as [type]
[ref]$SaveOption = "microsoft.office.interop.word.WdSaveOptions" -as [type]
$docs = Get-childitem -path $Path -Include $file -Recurse
$document = $application.documents.open($doc.fullname)

...

$document.close([ref]$saveOption::wdDoNotSaveChanges)

...

Regards, Scanta




powershell ise error

$
0
0
hi  I have windows 8.1 enterprise x64, when I want to enter  powershell ise tools option  powershell ise shows me  unexpected error  and  "close program"  How do i solve this problem

Powershell command to monitor GPO Replication

$
0
0
Any PS1 script to monitor GPO replication health and set it as a task scheduler which will trigger email everyday

Import/Export mailbox - what is included by default?

$
0
0

Hello! I think this is unclear in the documentation:

Will a new export request export the complete mailbox by default? Included contacts, calendar, online archive?


New-MailboxExportRequest -Mailbox Username -FilePath \\savelocation\username.pst


Kthxbai



SSL Configuration for Windows Remoting (WSMAN) [PS > winrm quickconfig -transport:https]

$
0
0

Hi,
I have the certificate with right cn for my domain joined server in cert store > local machine > personal but Winrm fails to find it? I ran the simular command on a standalone server  and it works easy.

Both Certs are issued by same Ent-CA 

PS C:\Windows\system32> winrm quickconfig -transport:https
WinRM service is already running on this machine.
WSManFault
    Message
        ProviderFault
            WSManFault
                Message = Cannot create a WinRM listener on HTTPS because this machine does not have an appropriate cert
ificate. To be used for SSL, a certificate must have a CN matching the hostname, be appropriate for Server Authenticatio
n, and not be expired, revoked, or self-signed.

Error number:  -2144108267 0x80338115
Cannot create a WinRM listener on HTTPS because this machine does not have an appropriate certificate. To be used for SS
L, a certificate must have a CN matching the hostname, be appropriate for Server Authentication, and not be expired, rev
oked, or self-signed.

----

Any Idea?

Cheers,

-Seyed

Unable to "MANAGE MSQM" from Failover Cluster Manager when a Clustered MSMQ is created using Powershell

$
0
0

Hi,

I am hoping someone would be able to help me as I have looked on the internet for an answer to this. We deploy a number of servers that are configured using Powershell. I am in the process of creating a clustered WIN2K8R2 cluster with MSMQ. I am able to do this successfully through the Failover Mgr with no issues.  In addition, I can do this via Powershell (code listed below) with one caveat.

However, when I create the same exact MSMQ in Powershell, I am unable to right click on the MSMQ service to manage it as the "Manage MSMQ" is missing when I right click on it. The settings are the same, including dependencies. The only difference I have been able to find is the icon in the Failover Manager shows the Service as a Generic Service icon when created in Powershell, but when it is created in the GUI it shows up as the MSMQ icon. I was able to verify this in the registry in HKLM\Cluster\Groups\<GUID>\: GroupType HEX: 68 for msmq icon. When it is the Generic Service icon it is HEX: 270f. When I change it from 270f to 68, the icon changes in Failover Manager and I am able to open, but then I get an invalid handle and I am unable to manage it.

This is causing an issue, because I want to automate this build and hand it over, but they would be unable to manage it except by programming which the operators are not ready for.

Here is the code which I have created in Powershell:

    Write-host "Configuring MS MSMQ Cluster Failover..."
    $CluName = "Cluster Name"
    $ClsMSMQName = $CluName.Name + "MSMQ"
    $ClsMSMQResourceName = "MSMQ-" + $ClsMSMQName
    $Response = Read-host "Enter the IP Address of the Clustered MSMQ"

    $ClsIpRes = get-clusterresource "Cluster IP Address"
    $MSMQIpAddr = New-Object Microsoft.FailoverClusters.PowerShell.ClusterParameter $ipres,Address,$Response

    Add-ClusterServerRole -Name $ClsMSMQName -Storage "Cluster Disk" -StaticAddress $MSMQIpAddr.value
    # Add the MSMSMQ Service to the new Server Role
    Get-ClusterGroup $ClsMSMQName | Add-ClusterResource -Name $ClsMSMQResourceName -ResourceType "MSMQ"
    # Create Dependencies for the MSMQ group
    Add-ClusterResourceDependency $ClsMSMQResourceName $ClsMSMQName
    Add-ClusterResourceDependency $ClsMSMQResourceName "Cluster Disk"
    # Start MSMQ group
    Start-ClusterGroup $ClsMSMQName

You would just have to change "Cluster Disk" and "Cluster Name".

Thank you



Powershell not merging files

$
0
0

Hi there,

I am literally hours new at Powershell scripting. I took on a project of developing a process that would scan a folder for presence of files matching a specific pattern:fileprefix.MMDDYYY.[a-z].dat (please note regex [a-z] where a to z represents  presence of a single letter only followed by file extension .dat).

So far I was able to come up with the code below:

## List of files available in target folder:
## asodent.20140829.a.dat, asodent.20140829.b.dat, asophys.20140827.a.dat, asophys.20140827.b.dat, asophys.20140827.c.dat

$asodent  = @(); $asoinst  = @(); $asopharm = @(); $asophrm  = @();$asophys  = @()
$filetype = @()
$date = ("{0:yyyy-MM-dd}" -f (get-date)) -replace "-",""

## file suffixes
$asodent_sufx =@(); $asoinst_sufx =@(); $asopharm_sufx =@(); $asophrm_sufx =@(); $asophys_sufx =@()


## 1 - Code defining and assigning suffixes values here
Foreach($filename in $Filelist){
    if ($filename -like "asodent.*")
        {
            $asodent += ,$filename
            $asodent_sufx = -join ($asodent_sufx + (($filename -replace('\.','-')) -split "(-)")[4])
            $filetype += ,(($filename -replace('\.','-')) -split "(-)")[0]
        }
    elseif ($filename -like "asoinst.*")
        {
            $asoinst += ,$filename
            $asoinst_sufx = -join ($asoinst_sufx + (($filename -replace('\.','-')) -split "(-)")[4])
            $filetype += ,(($filename -replace('\.','-')) -split "(-)")[0]
        }
    elseif ($filename -like "asopharm.*")
        {
            $asopharm += ,$filename
            $asopharm_sufx = -join ($asopharm_sufx + (($filename -replace('\.','-')) -split "(-)")[4])
            $filetype += ,(($filename -replace('\.','-')) -split "(-)")[0]
        }
    elseif ($filename -like "asophrm.*")
        {
            $asophrm += ,$filename
            $asophrm_sufx = -join ($asophrm_sufx + (($filename -replace('\.','-')) -split "(-)")[4])
            $filetype += ,(($filename -replace('\.','-')) -split "(-)")[0]
        }
    else{
            $asophys += ,$filename;
            $asophys_sufx = -join ($asophys_sufx + (($filename -replace('\.','-')) -split "(-)")[4])
            $filetype += ,(($filename -replace('\.','-')) -split "(-)")[0]
        }
}


## 2 - Determinig available file types to process based on process above (step 1)
$filetype = $filetype | select -uniq


## 3 - Stitching files together based on available types (see prior step)
Foreach ($type in $filetype)
    {
        if ($type = "asodent"){$suffix = $asodent_sufx}
        elseif($type = "asoinst"){$suffix = $asoinst_sufx}
        elseif($type = "asopharm_sufx"){$suffix = $asopharm_sufx}
        elseif($type = "asophrm_sufx"){$suffix = $asophrm_sufx}
        else{$suffix = $asophys_sufx}
        $combinedfile = $type + "."+ $date + "." + $suffix + ".dat"
        $string = $type +".*"


        Get-ChildItem | Where-Object {(-not $_.PSIsContainer) -and $_.Name -like $string} |
        % { Get-Content $_ -ReadCount 0 |
        Add-Content .\$combinedfile }
    }

cls
Write-Host "Process complete !"
Read-Host


I am having issues getting the script above to merge provided files (see script for details). It stops stitching them together after the first merge is processed. It does not complete the process by processing the second merge operation. Is there anything I am missing that is causing the script to stop the process halfway?  (it shows "Process complete" even though it did not kick off the second stitching operation).

Any help would be truly appreciated


Error troubleshooting in AD Module - Get-Aduser w/created filter

$
0
0

Hi All,

I'm working as an intern with my university, and I've been tasked with clearing out old student accounts in AD. There are currently over 4000 users in our system, and it's estimated that there are over 3500 old accounts that need to be deleted.

We are at the 2008 R2 Domain Functional Level.

I am going to script this through Powershell, but I'm having a terrible time getting a certain query to run properly.

I am using the following:

get-aduser -filter {created -lt'1/1/2010'-and lastlogontimestamp -notlike'*'} -properties created

I will sometimes narrow my query by adding another filter for created -gt '1/1/2008', for instance.

When I run the command as written, however, it will return several hundred users, but then it spits out the following error after the last displayed result:

Get-ADUser : The specified method is not supported
At C:\Users\Administrator.CSC\Desktop\test1.ps1:4 char:15+   get-aduser <<<< -filter {created -lt'1/1/2010'} -properties created | ft name,samaccountname,created+ CategoryInfo     : NotSpecified: (:) [Get-ADUser], ADException+ FullyQualifiedErrorId : The specified method is not supported,Microsoft.ActiveDirectory.Management.Commands.GetADUser

If I narrow my search scope by created date, I can sometimes get the error to not appear. My guess is that there are several accounts in the database that trigger the error (or at least, that's how it appears).

I have tried running this on both a DC and a non-dc server with server management tools installed. It doesn't matter what other filters are used, so omitting the lastlogontimestamp filter doesn't prevent the error.

My supervisor seems to think there may be errors in the AD database, but I've done every AD health check I can think of.

Does anyone have any suggestions?

 

Thanks,

Brandon

Get DataBase Size and Compare it

$
0
0

Hello Folks

I'm trying to get SQL 2008 R2 database size and compare it with this code:

$DBSize = Invoke-SQLCmd -Query "sp_databases" -Username "user" -Password "pwd" `
-ServerInstance "localhost" | where-object {$_.database_name -eq "ABC"} | select database_size

If(($DBSize | Out-String) -ge "5242880"){

# Some action #
              
}
But that don't return nothing... Some help !?


Jimcesse
Principal: http://sysadmin-cr.com/
Alterno: http://blogs.itpro.es/jimcesse

keep files from first of the month for a year

$
0
0

We have a series of folders with subfolders that have logfiles in them. Each folder has new log files generated daily. However on occasion, a log file is not generated for a day or for a few days.

I want to keep the log file in each folder for the first of each month, or as close to the day as possible for a year and delete all files older than a year. I also want to delete all files in that folder that are not from the first of the month.

So, on August 30, 2014 Folder 1 may have log files from each day in August except for August 1. When I run my script on September 1, I want the folder to have files:

August 02, 2014.log

July 01, 2014.log

June 01, 2014.log

If the first log file is August 5th, then I want to keep that one and delete the rest.

I currently have 30+ folders that get daily log files. It takes a long time to go into each folder, see which log is closest to the beginning of the month, delete the remaining files from that month, then find the log files from over a year ago and delete that one.

Ive tried a few iterations but, keep getting stuck. Any help would be appreciated.

Thanks!

Steve

PSRemoting Domain Controllers 2008 R2

$
0
0

I am new to powershell and ps remoting but I cannot get remoting to work on my DC's. I followed to same steps on non-DC and they work on the first try. All I am running is this command (Enable-PSRemoting -Force). I have tried turning off the firewall, Management Framework 3 & 4. On my non-DC systems I can connect using Enter-PSSession without issue. When connecting to the DCs here is what I get.

Enter-PSSession : Connecting to remote server failed with the following error message : The client cannot connect to the destination specified in the request. Verify that the service on the destination is 
running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the 
following command on the destination to analyze and configure the WinRM service: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.

I have also tested connections with (winrm) and again on the DCs I get this error.

WSManFault
  Message = The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig".

Error number:  -2144108526 0x80338012
The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig".

I have tried a lot of troubleshoot, tips, manual configurations and I keep coming up empty. The DCs are dedicated to domain services and DNS. I have two DCs, I am using a workstation in the domain. Any ideas?

Viewing all 21975 articles
Browse latest View live


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