Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

WMI Filter on various computer names

$
0
0

I am trying to create a WMI Filter for a GPO using  Win32_ComputerSystem using Name to filter the results.  The problem is when I try to add multiple values with Name I get a syntax error.

The statement looks like this

Select * From Win32_ComputerSystem where Name LIKE "ABCD%" or "EFGH%" or "IJKL%" AND Version like "6.%" or ProductType="3"

I get a syntax error when I tried to use the multiple Names.  If I remove "EFGH%" and "IJKL%" it works fine.  What am I missing?


How to migrate SQL Server Instance from Local Instance to Azure VM SQL using PowerShell dbatools ?

$
0
0

How to migrate SQL Server Instance from Local Instance to Azure VM SQL Server Instance?

Seeking for experts support resolving following issue.

Scenario:

LocalInstance: SQLSRV01

Azure VM: 23.96.20.20

-Local SQL SERVER and Azure VM SQL SERVER Instance are of SQLSERVER 2017 (14.0)

-Added Inbound port rule for sql server

-SharedPath accessible from both sides ( Local computer as well as from Azure VM: 23.96.20.20  )

-DBSERVER17 instance is accessible and connected from local computer

-Same command worked well at my local computer with two different SQL SERVER Instances.

Power Shell Script: 

$params = @{
 Source = "SQLSRV01"
 Destination = "23.96.20.20"
 SharedPath = "Z:"
 BackupRestore = $true
 }
 Start-DbaMigration @params -Force | Select * | Out-GridView

Output Received:

PS C:\WINDOWS\system32> E:\PowerShellScripts\RemoteInstance.ps1
WARNING: [16:05:58][Copy-DbaSpConfigure] Error occurred while establishing connection to 23.96.20.20 | The wait operat
ion timed out
WARNING: [16:06:15][Copy-DbaCustomError] Error occurred while establishing connection to 23.96.20.20 | The wait operat
ion timed out
WARNING: [16:06:15][Copy-DbaCredential] Console not elevated, but elevation is required to perform some actions on loc
alhost for this command.
WARNING: [16:06:15][Copy-DbaDbMail] Error occurred while establishing connection to 23.96.20.20 | The wait operation t
imed out
WARNING: [16:06:15][Copy-DbaRegServer] Error occurred while establishing connection to 23.96.20.20 | The wait operatio
n timed out
WARNING: [16:06:15][Copy-DbaBackupDevice] Error occurred while establishing connection to 23.96.20.20 | The wait opera
tion timed out
WARNING: [16:06:15][Copy-DbaInstanceTrigger] Error occurred while establishing connection to 23.96.20.20 | The wait op
eration timed out
WARNING: [16:06:15][Copy-DbaDatabase] Error occurred while establishing connection to 23.96.20.20 | The wait operation
 timed out
WARNING: [16:06:15][Copy-DbaLogin] Error occurred while establishing connection to 23.96.20.20 | The wait operation ti
med out
The wait operation timed out
At C:\Program Files\WindowsPowerShell\Modules\dbatools\1.0.113\allcommands.ps1:83435 char:9
+         throw $records[0]
+         ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], Exception
    + FullyQualifiedErrorId : dbatools_Connect-DbaInstance



Script Modification for Top 10 Senders

$
0
0

Hello,

First of all Thank You for Richard L. Mueller as he helped me for this script very long back.

I have following script which I've been using manually in daily basis. But how to modify and make it schedule & which can be sending through e-mail attachment with .csv report to couple recipients in daily basis.

Example :

From : Admin@company.com

To : user1@company.com, user2@company.com, user3@company.com

Subject : Top Senders

==========================================================================================================

#mjolinor
#02/24/2011
#requires -version 2.0

$today = get-date
$rundate = $($today.adddays(-1)).toshortdatestring()
$outfile_date = ([datetime]$rundate).tostring("yyyy_MM_dd")
$outfile = "email_stats_" + $outfile_date + ".csv"
$dl_stat_file = "DL_stats.csv"
$accepted_domains = Get-AcceptedDomain |% {$_.domainname.domain}
[regex]$dom_rgx = "`(?i)(?:" + (($accepted_domains |% {"@" + [regex]::escape($_)}) -join "|") + ")$"
$mbx_servers = Get-ExchangeServer |? {$_.serverrole -match "Mailbox"}|% {$_.fqdn}
[regex]$mbx_rgx = "`(?i)(?:" + (($mbx_servers |% {"@" + [regex]::escape($_)}) -join "|") + ")\>$"
$msgid_rgx = "^\<.+@.+\..+\>$"
$hts = get-exchangeserver |? {$_.serverrole -match "hubtransport"} |% {$_.name}
$exch_addrs = @{}
$msgrec = @{}
$bytesrec = @{}
$msgrec_exch = @{}
$bytesrec_exch = @{}
$msgrec_smtpext = @{}
$bytesrec_smtpext = @{}
$total_msgsent = @{}
$total_bytessent = @{}
$unique_msgsent = @{}
$unique_bytessent = @{}
$total_msgsent_exch = @{}
$total_bytessent_exch = @{}
$unique_msgsent_exch = @{}
$unique_bytessent_exch = @{}
$total_msgsent_smtpext = @{}
$total_bytessent_smtpext = @{}
$unique_msgsent_smtpext=@{}
$unique_bytessent_smtpext = @{}
$dl = @{}
$obj_table = {
@"
Date = $rundate
User = $($address.split("@")[0])
DisplayName = $($ExtraInfo.DisplayName)
Alias = $($ExtraInfo.Alias)
Domain = $($address.split("@")[1])
Sent Total = $(0 + $total_msgsent[$address])
Sent MB Total = $("{0:F2}" -f $($total_bytessent[$address]/1mb))
Received Total = $(0 + $msgrec[$address])
Received MB Total = $("{0:F2}" -f $($bytesrec[$address]/1mb))
Sent Internal = $(0 + $total_msgsent_exch[$address])
Sent Internal MB = $("{0:F2}" -f $($total_bytessent_exch[$address]/1mb))
Sent External = $(0 + $total_msgsent_smtpext[$address])
Sent External MB = $("{0:F2}" -f $($total_bytessent_smtpext[$address]/1mb))
Received Internal = $(0 + $msgrec_exch[$address])
Received Internal MB = $("{0:F2}" -f $($bytesrec_exch[$address]/1mb))
Received External = $(0 + $msgrec_smtpext[$address])
Received External MB = $("{0:F2}" -f $($bytesrec_smtpext[$address]/1mb))
Sent Unique Total = $(0 + $unique_msgsent[$address])
Sent Unique MB Total = $("{0:F2}" -f $($unique_bytessent[$address]/1mb))
Sent Internal Unique = $(0 + $unique_msgsent_exch[$address])
Sent Internal Unique MB = $("{0:F2}" -f $($unique_bytessent_exch[$address]/1mb))
Sent External Unique = $(0 + $unique_msgsent_smtpext[$address])
Sent External Unique MB = $("{0:F2}" -f $($unique_bytessent_smtpext[$address]/1mb))
"@
}
$props = $obj_table.ToString().Split("`n")|% {if ($_ -match "(.+)="){$matches[1].trim()}}
$stat_recs = @()
function time_pipeline {
param ($increment = 1000)
begin{$i=0;$timer = [diagnostics.stopwatch]::startnew()}
process {
  $i++
  if (!($i % $increment)){Write-host “`rProcessed $i in $($timer.elapsed.totalseconds) seconds” -nonewline}
  $_
  }
end {
  write-host “`rProcessed $i log records in $($timer.elapsed.totalseconds) seconds”
  Write-Host "  Average rate: $([int]($i/$timer.elapsed.totalseconds)) log recs/sec."
  }
}
foreach ($ht in $hts){
 
  Write-Host "`nStarted processing $ht"
 
  get-messagetrackinglog -Server $ht -Start "$rundate" -End "$rundate 11:59:59 PM" -resultsize unlimited |
  time_pipeline |%{
  
  
  if ($_.eventid -eq "DELIVER" -and $_.source -eq "STOREDRIVER"){
  
    if ($_.messageid -match $mbx_rgx -and $_.sender -match $dom_rgx) {
      
      $total_msgsent[$_.sender] += $_.recipientcount
      $total_bytessent[$_.sender] += ($_.recipientcount * $_.totalbytes)
      $total_msgsent_exch[$_.sender] += $_.recipientcount
      $total_bytessent_exch[$_.sender] += ($_.totalbytes * $_.recipientcount)
    
      foreach ($rcpt in $_.recipients){
      $exch_addrs[$rcpt] ++
      $msgrec[$rcpt] ++
      $bytesrec[$rcpt] += $_.totalbytes
      $msgrec_exch[$rcpt] ++
      $bytesrec_exch[$rcpt] += $_.totalbytes
      }
      
    }
    
    else {
      if ($_messageid -match $messageid_rgx){
          foreach ($rcpt in $_.recipients){
            $msgrec[$rcpt] ++
            $bytesrec[$rcpt] += $_.totalbytes
            $msgrec_smtpext[$rcpt] ++
            $bytesrec_smtpext[$rcpt] += $_.totalbytes
          }
        }
    
      }
        
  }
  
  
  if ($_.eventid -eq "RECEIVE" -and $_.source -eq "STOREDRIVER"){
    $exch_addrs[$_.sender] ++
    $unique_msgsent[$_.sender] ++
    $unique_bytessent[$_.sender] += $_.totalbytes
    
      if ($_.recipients -match $dom_rgx){
        $unique_msgsent_exch[$_.sender] ++
        $unique_bytessent_exch[$_.sender] += $_.totalbytes
        }
 
      if ($_.recipients -notmatch $dom_rgx){
        $ext_count = ($_.recipients -notmatch $dom_rgx).count
        $unique_msgsent_smtpext[$_.sender] ++
        $unique_bytessent_smtpext[$_.sender] += $_.totalbytes
        $total_msgsent[$_.sender] += $ext_count
        $total_bytessent[$_.sender] += ($ext_count * $_.totalbytes)
        $total_msgsent_smtpext[$_.sender] += $ext_count
         $total_bytessent_smtpext[$_.sender] += ($ext_count * $_.totalbytes)
        }
               
      
    }
    
  if ($_.eventid -eq "expand"){
    $dl[$_.relatedrecipientaddress] ++
    }
  }  
  
}
foreach ($address in $exch_addrs.keys){
$ExtraInfo = Get-Mailbox -Identity $address
$stat_rec = (new-object psobject -property (ConvertFrom-StringData (&$obj_table)))
$stat_recs += $stat_rec | select $props
}
$stat_recs | export-csv $outfile -notype
if (Test-Path $dl_stat_file){
  $DL_stats = Import-Csv $dl_stat_file
  $dl_list = $dl_stats |% {$_.address}
  }
else {
  $dl_list = @()
  $DL_stats = @()
  }
$DL_stats |% {
  if ($dl[$_.address]){
    if ([datetime]$_.lastused -le [datetime]$rundate){
      $_.used = [int]$_.used + [int]$dl[$_.address]
      $_.lastused = $rundate
      }
    }
}
$dl.keys |% {
  if ($dl_list -notcontains $_){
    $new_rec = "" | select Address,Used,Since,LastUsed
    $new_rec.address = $_
    $new_rec.used = $dl[$_]
    $new_rec.Since = $rundate
    $new_rec.lastused = $rundate
    $dl_stats += @($new_rec)
  }
}
$dl_stats | Export-Csv $dl_stat_file -NoTypeInformation -force
Write-Host "`nRun time was $(((get-date) - $today).totalseconds) seconds."
Write-Host "Email stats file is $outfile"
Write-Host "DL usage stats file is $dl_stat_file"
#Contact information
#[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

====================================================================================================

Thanks in Advanced.


Regards,Ali

How to change StrongAuthenticationRequirements.State using PowerShell (MSOL)

$
0
0

Hi,
According to this article: https://docs.microsoft.com/en-us/azure/active-directory/authentication/howto-mfa-userstates#use-powershell I should be able to disabling MFA using PowerShell with simple array clearing: Get-MsolUser -UserPrincipalName < UserPrincipalName> | Set-MsolUser -StrongAuthenticationRequirements @(), but param StrongAuthenticationRequirements.State always remains "Enabled". Do someone have idea why it doesn't work as it should? I found that when MFA is disable then param StrongAuthenticationRequirements.State have no value at all. When I assing a $null to this param it doesn't work too. I know I can easly do it from O365 Portal but really need to have a script for support line. 



Install Fonts using a Batch File... Need Help getting the coding correct.

$
0
0

I have been on the internet and looked at multiple sites that give suggestions on how to install fonts on a local workstation using a batch. I can't seem to get them to work. I am hoping that some one can give me a script to use a as a batch that will allow me to install fonts on to workstations. Also put them in the registry.

Maybe even get some one to breakdown to me line by line the code that i have to get this to work on my workstation.

The sites i have looked at include

http://blogs.technet.com/b/heyscriptingguy/archive/2008/04/25/how-can-i-install-fonts-using-a-script.aspx

http://answers.microsoft.com/en-us/windows/forum/windows_7-files/bat-install-a-ttf/bb86b8c0-c3d5-44d1-b990-d7f42bc95b87

http://drbatcher.blogspot.com/2010/01/installing-fonts-using-batch-files.html

powershell script to delete files worsk with 64bit 32bit dosent work

$
0
0
 if ((Get-WmiObject win32_operatingsystem | select osarchitecture).osarchitecture -like "64*")
{
#64bit code here
Write-Output 64bit

  if ((test-path -LiteralPath "$fileToCheck3") -like "True*")
  {
  cmd.exe /C "$fileToCheck3" /cleanup:all /q /w
  }

    if ((Test-Path -LiteralPath "$fileToCheck") -like "True*")
    {
     Write-Output Del user files 64bit 
     cmd.exe /c rmdir /Q /S "$fileToCheck"
    }
}
 
else
{
#32bit code here
Write-Output 32bit
if ((test-path -LiteralPath "$fileToCheck4") -like "True*")
{
    {
     cmd.exe /C "$fileToCheck4" /cleanup:all /q /w
    } 

    if ((Test-Path -LiteralPath "$fileToCheck") -like "True*")
    {
     Write-Output Del user files 32bit 
     cmd.exe /c rmdir /Q /S "$fileToCheck"
    }
}
 }
 }

how to use Connect-MicrosoftTeams in script

$
0
0

Hi,

I am trying to use Connect-MicrosoftTeams command and assign users to teams in Teams with scheduled script, according to group membership in AD. However, I have to always authenticate and also manually click on "Pick an account" dialog window.

$mycreds=Get-Credential #in script I saved my credential in encrypted string

Connect-MicrosoftTeams -Credential $mycreds -AccountId "account@domain.com"

How can I use this command and successfully log-in to cloud service with no user interaction ?

Question about this script "Write to HKCU from the system account"

$
0
0

So this is the original script: https://gallery.technet.microsoft.com/scriptcenter/Write-to-HKCU-from-the-3eac1692#content

My question is, can you help me add reverse function to this script, to export "some" HKCU key to .reg as system account.

Thanks for your help.


powershell script to delete files works with 64bit dosent delete folders with 32bit

$
0
0
Invoke-Command -ComputerName      -Credential  -ScriptBlock {


$fileToCheck = "$env:LOCALAPPDATA\Microsoft\Windows Live Mail"

$fileToCheck2 = "$env:APPDATA\Thunderbird\profiles.ini"

$fileToCheck3 = "C:\program files (x86)\windows live\installer\wlarp.exe"

$fileToCheck4 = "C:\program files\windows live\installer\wlarp.exe"

if((get-process "wlmail" -ea SilentlyContinue) -eq $Null)
{ 

    if ((Get-WmiObject win32_operatingsystem | select osarchitecture).osarchitecture -like "64*")
{
#64bit code here
Write-Output 64bit

if (test-path -LiteralPath "$fileToCheck3") 
{
cmd.exe /C "$fileToCheck3" /cleanup:all /q /w
}

    if (Test-Path -LiteralPath "$fileToCheck") 
    {
     Write-Output Del user files 64bit 
     cmd.exe /c rmdir /Q /S "$fileToCheck"
    }
}
else
{
#32bit code here
Write-Output 32bit

if (test-path -LiteralPath $fileToCheck4) 
{   
 cmd.exe /C $fileToCheck4 /cleanup:all /q /w
} 

    if (Test-Path "$fileToCheck") 
    {
     Write-Output Del user files 32bit 
     cmd.exe /c rmdir /Q /S "c:\Users\Kauplus\AppData\Local\Microsoft\Windows Live Mail"
    }
}
}
else
{ 
    Stop-Process -Name wlmail 
if ((Get-WmiObject win32_operatingsystem | select osarchitecture).osarchitecture -like "64*")
{
#64bit code here
Write-Output 64bit wlmain 

  if (test-path -LiteralPath "$fileToCheck3") 
  {
  cmd.exe /C "$fileToCheck3" /cleanup:all /q /w
  }

    if (Test-Path -LiteralPath "$fileToCheck") 
    {
     Write-Output Del user files 64bit 
     cmd.exe /c rmdir /Q /S "$fileToCheck"
    }
}
else
{
#32bit code here
Write-Output 32bit  wlmain 

if (test-path -LiteralPath "$fileToCheck4") 
    {
     cmd.exe /C "$fileToCheck4" /cleanup:all /q /w
    } 

    if (Test-Path -LiteralPath "$fileToCheck") 
    {
     Write-Output Del user files 32bit 
     cmd.exe /c rmdir /Q /S "$fileToCheck"
    }
}
 }
 }



Adding a variable to Octopus Deploy project issues

$
0
0

Hi,

I am adding a variable to a Octopus Project and I cant get it to work. I am getting an error - 

You cannot call a method on a null-valued expression.

$project.Variables.AddOrUpdateVariableValue($newVariable)

My $newVaraible returns what it should so I cant see why it is giving me a null error.

Code:

    $endpoint = New-Object Octopus.Client.OctopusServerEndpoint $OctopusUrl,$APIKey 
    $client = New-Object Octopus.Client.OctopusClient $endpoint

    $space = $client.ForSystem().Spaces.FindByName($SpaceName) 
    $spaceRepository = $client.ForSpace($space)

    #Add a new variable to the project
    $newVariable = New-Object Octopus.Client.Model.VariableResource
    $newVariable.Name = "PackageName"
    $newVariable.Value = "Package.Common.DataConcerns"

    # Find the project you want and add the variable to
    foreach ($name in $ProjectName) {
        $project = $spaceRepository.Projects.FindByName($name)
        $project.Variables.AddOrUpdateVariableValue($newVariable)
        $spaceRepository.Projects.Modify($project)
        
    }


Create Multi-level folder or item in different PSDrive with powershell

$
0
0
Hi scripting Guys 
When come to  different PSDrive like FileSystem Registry or MDTProvider,you want to Create  Multi-level directory or folder or item
in FileSystem we have  Four Ways to realize it such as system.io.directory class Scripting.FilesystemObject or command new-item  md 
but when i manage MDT use PowerShell Cmdlets to create Multi-level  folder in the PSDrive of MDTProvider 
it runs into a stone wall ,in this case I  want to create "3-levels" folder under  "Out-of-Box Drivers" ,The fullpath like 
"$MDTPSDriveName :\Out-of-Box Drivers\$OSVersion\$structural\$Model "  
maybe $OSVersion="Windows  10",$structural ="x64,x86" ,$Model="HP480 G4,Lenovo B40-80" 
the example command  
new-item -path "MDTPSDriveName:\Out-of-Box Drivers\Windows 10\x64\HP ProDesk 480 G4 " -enable "True" -Name "Windows 10" -Comments "" -ItemType "folder" -Verbose
but it didn't  work  because the parent directory does not exist. and except create folder step-by-step can we have a similar way to create  Multi-level  folder directly

How to find all properties of RecordData from Get-DnsServerResourceRecord

$
0
0

When I use Get-DnsServerResourceRecord I can obviously get the zone details, but I'm trying to do a select-object on the RecordData column which isn't straight forward since it's not a simple text string.

What I've found so far... I can query specific properties of RecordData to query types of record, for instance :

Get-DnsServerResourceRecord -zonename "myzone.com" | where-object {$_.RecordData.nameserver -match "ns1"}

Get-DnsServerResourceRecord -zonename "myzone.com" | where-object {$_.RecordData.ipv4address -match "192.168"}

will let me query NS records and A record IP addresses.

How do I find the other properties available from RecordData other than nameserver and ipv4address? Presumably there must also be properties for MX records, CNAME records, Text records, IPv6 records etc, but I can't work out how to find what they are.

LDAP issue with powershell

$
0
0

Hello,

I have created one PowerShell script to get the Active directory data. In which I used Active Directory Domain Services to get the data. 

I am using the JSON file to provide the Input.

The command is as below

"$allGroups = Find-LdapObject -SearchFilter $settings.ldapSettings.Filter -SearchBase $settings.ldapSettings.BasePath -LdapConnection $ADDPConnect

        -PageSize $settings.ldapSettings.PageSize -PropertiesToLoad $settings.ldapSettings.PropertiesToLoad -BinaryProperties $settings.ldapSettings.BinaryPropertiesToLoad"

but it giving me error "The object does not exist".

" ERROR: System.Management.Automation.MethodInvocationException: Exception calling "SendRequest" with "2" argument(s): "The object does not exist." ---> System.DirectoryServices.Protocols.DirectoryOperationException: The object does not exist.

   at System.DirectoryServices.Protocols.LdapConnection.ConstructResponse(Int32 messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, Boolean exceptionOnTimeOut)

   at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout)

   at CallSite.Target(Closure , CallSite , LdapConnection , Object , Object )

   --- End of inner exception stack trace ---

   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)

   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)

   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)

   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)

   at System.Management.Automation.PSScriptCmdlet.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess)

   at System.Management.Automation.PSScriptCmdlet.DoProcessRecord()

   at System.Management.Automation.CommandProcessor.ProcessRecord()"

Am I missing something in this?

Thank you.

How to remove security permission from OU using command

$
0
0

We had delegated permission at OU level for some security groups. Since there are too many OUs so we had used DSACLS command. Now we have to remove permission from OU.

Example

Group A currently has permission at OU "India" to create create object and delete object but now I want to remove A completely from India OU so how can I do it from script?


Arif

Unable to Automate RDP Using PowerShell

$
0
0

Hi Team,

I have Azure - Windows Server 2016 VMs that are being used for testing. so i have a requirement where i need to Remote desktop into these machines and run my test. In this process i wanted to automate the whole RDP process.

I checked online for powershell scripting to do that as per below 

$Server   = "AzureVMName"
$User     = "UserName"
$Password = "password"

cmdkey /delete:"$Server"
cmdkey /generic:"$Server" /user:"$user" /pass:"$password"

mstsc /v:"$Server" /admin

But the problem is when i run the above in powershell , still i get the windows pop up for password entry. Once i enter the password manually i get a pop up of certificate acceptance. As i have to run the tests as  a business requirement , i can't even modify the policies to do the changes as per IT security reasons.

So how can i achieve automating the whole RDP process - is there any way using powershell, if not possible can anybody suggest any tool or way of getting this automated withput changing any local security policies.

Regards,

Ranjan


Unable to Enlist Target to MSX after Collation Change.

$
0
0

Hi folks,

After changing the Collation of SQL Server to Latin1_General_CI_AI from QL_Latin1_General_CP1_CI_AS  I'm trying to add the server to MSX as target in CMS but Enlisting is failing. One thing I forgot to do before SQL Collation change was defecting the server. Now I'm not sure if it is because of not defecting the server or changing collation that has caused this? Regardless, now I need to enlist the server in MSX and push monitoring jobs. This same server was enlisted before the change. 

I'm able to connect to the target server from CMS and vice versa using SSMS.

Target SQL Server Version: 2017

CMS SQL Server Version: 2017

Error when trying to enlist from CMS:

===================================

MSX enlist failed for JobServer 'myserver.domain.sa'.  (Microsoft.SqlServer.Smo)

------------------------------
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=14.0.17285.0+((SSMS_Rel_17_4).180821-0238)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=MSX+enlist+JobServer&LinkId=20476

------------------------------
Program Location:

   at Microsoft.SqlServer.Management.Smo.Agent.JobServer.MsxEnlist(String masterServer, String location)
   at Microsoft.SqlServer.Management.SqlManagerUI.EnlistTsxActions.DoAction(ProgressItemCollection actions, Int32 index)
   at Microsoft.SqlServer.Management.SqlStudio.Controls.ProgressItemCollection.DoWorkOnThread()

===================================

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

------------------------------
Program Location:

   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(StringCollection sqlCommands, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQuery(StringCollection queries, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.Agent.JobServer.MsxEnlist(String masterServer, String location)

===================================

The enlist operation failed (reason: The time-out was exceeded while the server waited for a response from SQL Server Agent. Make sure that the SQL Server Agent service is running) (.Net SqlClient Data Provider)

------------------------------
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=14.00.3281&EvtSrc=MSSQLServer&EvtID=22026&LinkId=20476

------------------------------
Server Name: myserver.domain.sa
Error Number: 22026
Severity: 16
State: 1


------------------------------
Program Location:

   at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)

Error when trying to Add this as target from target server:

===================================

MSX enlist failed for JobServer 'myserver.domain.sa'.  (Microsoft.SqlServer.Smo)

------------------------------
For help, click: https://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=15.0.18206.0+((SSMS_Rel).191029-2112)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=MSX+enlist+JobServer&LinkId=20476

------------------------------
Program Location:

   at Microsoft.SqlServer.Management.Smo.Agent.JobServer.MsxEnlist(String masterServer, String location)
   at Microsoft.SqlServer.Management.SqlManagerUI.EnlistTsxActions.DoAction(ProgressItemCollection actions, Int32 index)
   at Microsoft.SqlServer.Management.SqlStudio.Controls.ProgressItemCollection.DoWorkOnThread()

===================================

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

------------------------------
Program Location:

   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(StringCollection sqlCommands, ExecutionTypes executionType, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQuery(StringCollection queries, Boolean retry)
   at Microsoft.SqlServer.Management.Smo.Agent.JobServer.MsxEnlist(String masterServer, String location)

===================================

The enlist operation failed (reason: The time-out was exceeded while the server waited for a response from SQL Server Agent. Make sure that the SQL Server Agent service is running) (.Net SqlClient Data Provider)

------------------------------
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=14.00.3281&EvtSrc=MSSQLServer&EvtID=22026&LinkId=20476

I can't seem to find much information online on this issue. Any help would be appreciated. 




Error "Send-MailMessage : An invalid character was found in the mail header: '@'."

$
0
0

I am trying to write the script to automate (using scheduler) departing AD user disabling.

Script I gobbled up:

"

$bfile = "C:\Temp\disable.bat"
$fromaddress = "<somegroup>@ssa.gov"
$user = Read-Host -Prompt "Please enter a username"
$usepath = Get-ADUser -Identity $user -Properties DistinguishedName | Select-Object DistinguishedName


$usepath -match "@{DistinguishedName=(?<content>.*)}"
$string = $matches
'dsmod user ' + $string['content'] + '-disabled yes' | Out-File -Filepath $bfile

$usemail = Get-ADUser -Identity $user -Properties mail | Select-Object mail
$usemail -match "@{mail=(?<content>.*)}" 
$string1 = $matches

$gname = Get-ADUser -Identity $user -Properties GivenName | Select-Object GivenName
$gname -match "GivenName=(?<content>.*)}"
$string2 = $matches
$string2 | Out-File -Filepath  $nfile


$properties = @{
    to         = "$usemail"
    from       = "$fromaddress"
    subject    = "Please remember to return SSA propery"
    smtpserver = "Dear $gname, Please remember to return SSA Badge, laptop and any other SSA property you might have"
}

Send-MailMessage @properties

"

First part works and successfully generates the batch file but email part throws an error: "Send-MailMessage : An invalid character was found in the mail header: '@'."

Please help!

Setting AD attribute EmployeeType for all users

$
0
0

I am trying to set the employeeType attribute based on title for all users in the company.  If the title attribute contains the word "intern" the employeeType should be set to "Intern".  If the title attribute contains the word"contractor" the employeeType should be set to "Contractor".  All other non-blank titles should set the employeeType to "Employee".  The title is null for service accounts, admin accounts, test accounts, etc and the employeeType should be null also.

The PowerShell code below basically works, but it seems inefficient to process the whole AD three times.  Do you have suggestions on cleaning up the code?  Thanks.

Get-ADUser -Filter * -Properties * | ? {$_.title -Like '*intern*'} | Set-ADUser -Replace @{employeeType='Intern'}
Get-ADUser -Filter * -Properties * | ? {$_.title -Like '*contractor*'} | Set-ADUser -Replace @{employeeType='Contractor'}
Get-ADUser -Filter * -Properties * | ? {($_.title -ne $null) -and ($_.title -NotLike '*intern*') -and ($_.title -NotLike '*contractor*')} | Set-ADUser -Replace @{employeeType='Employee'}

Broken ForEach Command

$
0
0

hey all,

I'm trying to create some AD groups en mass and I got the names in a CSV file that has been imported successfully, but my ForEach command isn't creating the groups, and it's not generating an error.  Not sure what's going on there, but here is my code:

Import-Module ActiveDirectory
$groups = Import-Csv C:\Users\myuser\Desktop\groups.csv

ForEach ($group in $group) {New-ADGroup -Name $group.name -Path “OU=Groups,OU=Department,DC=domain,DC=com” -GroupCategory Security -GroupScope Universal 
}

I haven't tried taking the last bits off, but I think they need to be defined.  Any thoughts help!


Please remember to click "Mark as Answer" on the post that helps you, and to click "Unmark as Answer" if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

Script to zip file

$
0
0

Currently we are backing up all our event logs to one primary file server but as time passed, the size grew tremendously. I am currently looking for a script which I can execute monthly to zip-up the event logs to the archive folder, naming the zip file according to year+month and delete the event logs once it runs successfully.

Example below are the file structure, inside the D:\EventLog, there are subfolder which stores the event logs. What I would like to do is to have a script which can zip the event logs on a certain months, copy to the archive folder and delete the events at the D:\EventLog



Viewing all 15028 articles
Browse latest View live


Latest Images

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