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

Check if SQL Server service account is local admin and if so remove it as admin

$
0
0

I have been trying to get below code to work - check 1st what is running sql server service and check if that service account is local admin on machine if so remove it:

        

[string]$sqlInstance 

$sqlInstance = 'TEST'

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SqlWmiManagement”) | out-null

$SMOWmiserver = New-Object (‘Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer’) $sqlInstance #pull in the server you want    


$SMOWmiserver.Services | Select-Object name, type, ServiceAccount, DisplayName | where {$_.type -eq “SqlServer” -and $_.displayName -eq "SQL Server (MSSQLSERVER)"} | Select-object ServiceAccount -outvariable $name

   Get-LocalGroupMember -group 'administrators' -member $name

   Remove-LocalGroupMember -group 'administrators' -member $name

I keep getting the error: for both get and remove:

Remove-LocalGroupMember -group 'administrators' -member $name
Remove-LocalGroupMember : Cannot bind parameter 'Member'. Cannot convert value "@{ServiceAccount=domain\usertest}" to type 
"Microsoft.PowerShell.Commands.LocalPrincipal". Error: "Cannot convert the "@{ServiceAccount=domain\usertest}" value of type 
"Selected.System.Management.Automation.PSCustomObject" to type "Microsoft.PowerShell.Commands.LocalPrincipal"."
At line:2 char:60
+    Remove-LocalGroupMember -group 'administrators' -member $name
+                                                            ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Remove-LocalGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.RemoveLocalGroupMemberCommand

I have tried hardcoding the value to get and remove then it works:


   Get-LocalGroupMember -group 'administrators' -member 'domain\usertest'

I think something is wrong with the way conversion is happening for my $name variable from where i set to use it. 

Appreciate any help i can get. Thanks


RPSAdmin


Powershell Check number of words in Line-SOLVED

$
0
0

i have variable $name

it contains John Doe string

I want to check if line contains 2 or more that 2 words

If it contains 2 words (John Doe) create new variable which will consist from first word of First name and append Last name

(JDoe), if $body variable contains more than 2 words (John JR Doe) create this variable: JJRDoe (append First Name Character) with other Words

I manged only to extract first word

$fname = $name.split(" ")[0]

$lname = $name.split(" ")[1]

so i cat get John and can get last name

But no idea how to check if there are 2 or three words



Uninstall Existing Software then Install New Software

$
0
0

Hi to all. I have a requirement to uninstall three applications in an enterprise environment. When the uninstall completes I must then re-install one of the applications (limitation of the product, need to enable features via command line). The script will be pushed out via SCCM. Unfortunately I am not a coder!

I have performed the usual searches and found some good articles and example scripts for uninstall.

https://www.enhansoft.com/using-powershell-to-uninstall-applications/

https://home.configmgrftw.com/uninstall-software-en-masse/

Question: How can I combine both uninstall and install in a single script. The install should only proceed if the uninstall was successful.

Using Garth Jones script as an example...

$appToMatch = 'My Application 1','My Application 2','My Application 3'
$e=$MyInvocation.InvocationName
$pshome
$log=$env:temp+'\PSuninstall.log'


function Get-InstalledApps
{
    Log-write $log 'Start Get-InstalledApps'
    if ([IntPtr]::Size -eq 4) {
        $regpath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
        Log-write $log 'Found x86'
    }
    else {
        $regpath = @(
            'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
            'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
        )
        Log-write $log 'Found x64'
    }
    Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} | Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |Sort DisplayName
}

Function Log-Write{
  Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LineValue) 
    
   Process{ 
     Add-Content -Path $LogPath -Value $LineValue 
   } 
} 


Log-write $log 'Startinging script'

#if running in x86 mode restart in x64 mode.
if ($PSHome -match 'syswow')
{
    Log-write $log 'Found syswow'
    Log-write $log 'Shell to x64 version'
    start-process "C:\Windows\sysnative\WindowsPowerShell\v1.0\powershell.exe" -arg "-ExecutionPolicy bypass  -file $e" -Wait
    Log-write $log 'Return from x64 version; exiting'
    exit
}



$result = Get-InstalledApps | where {$_.DisplayName -like $appToMatch}
$result 

Log-write $log 'Found these isntalled apps:'
ForEach ($u in $result) 
{
    $UnInstall = $u.UninstallString 
    $UnInstall = $UnInstall.Trim()
    $UnInstall = $UnInstall -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
    $UnInstall = $UnInstall.Trim()
    Log-write $log $UnInstall
    Log-write $log 'Start MSIExec'
    start-process "msiexec.exe" -arg "/X $UnInstall /qn /l*v $env:TEMP\$UnInstall.log" -Wait
    Log-write $log 'After MSIExec'
} 
GO
Start-Process 'C:\Software\MyApp.exe' /install /quiet /norestart -l %SystemRoot%\Temp\InstallLog.txt

Any help much appreciated.

Kind Regards,

Phil.

Extract just value of property

$
0
0

Hi,

I am sure that this is very easy but I have spent some time and cannot figure it out.

Please see below code:

"PS C:\WINDOWS\system32> $tenantid

TenantId
--------
94485bea-00a3-4535-93c6-5d8ee13109a1"

For the above code, how would I be able to extract out just the value of the variable tenantid to make my script work?

Any help would be most appreciated.

Thanks


 

How to script a list of Scheduled Tasks on your Domain

$
0
0
Is it possible to scan a list of computers (text file) and found the scheduled tasks with the times they run

New VBScript error - was for years working, today it does not.

$
0
0

I have a script on my servers that pulls data for running time of our equipment. It's been running fine for years, every day task scheduler kicks it off and it generates a text file report. This morning, the VBScripts fails (on all servers that have been running the script) with the error:

"Script:

' path to script...'.vbs

Line: 2

Char: 1

Error: Subscript out of range

Code: 800A0009

Source: Microsoft VBScript runtime error"

The code giving error start with this:

Set args = WScript.Arguments
strServerName = args.Item(0)
strUnitNum = Right(strServername,1)
strChannelName= "'" & strUnitNum & "_DB_HEATG'"

'wscript.Echo strServerName,strUnitNum

dblValue = 0.00

dteToday = Date

I have searched for the error and the articles are all older with resolutions that are not applicable so I am at a loss. Something changed on something, but the script that was working no longer does, so I do not expect it is the actual vbscript code causing the problem.

VBScript compilation error: Expected statement

$
0
0

Greetings,

I am new to vbscript so pardon the newbie question. I have started on a task to get files from an ftp server, read the file and insert the data into a DB. This question is regarding the error I get when I try to run the script. I am on a Windows Server 2008 R2 Standard, I have downloaded WinSCP and registered it. Below is the code I am trying to run with the command "cscript.exe getFiles.exe". When I run this command I get the error "VBScript compilation error: Expected statement". It points to line 41 col 2 which is the line with "End Using"


Any ideas on how to resolve this would be greatly appreciated. Below is the code, I have included the comment lines in case that has anything to do with it.

Regards,

Joe



set filename = "/directory/sample.xml"
' Default folder where files will be placed on the local server
set uploadFolder = "c:\ftp_files\"

Try
    ' Setup session options
    'Dim sessionOptions As New SessionOptions
    set sessionOptions = CreateObject("WinSCP.SessionOptions")
    With sessionOptions
        .Protocol = Protocol.Sftp
        .HostName = "ftp_server.com"
        .UserName = "user"
        .Password = "pwd"
        .SshHostKeyFingerprint = "xxxxxxxxxxx"
    End With

    set session = CreateObject("WinSCP.Session")
    'Using session As New Session
    Using session
        ' Connect
        session.Open(sessionOptions)

        ' Download files
        'Dim transferOptions As New TransferOptions
        set transferOptions = CreateObject("WinSCP.TransferOptions")
        transferOptions.TransferMode = TransferMode.Binary

        'Dim transferResult As TransferOperationResult
        set transferResult = CreateObject("WinSCP.TransferOperationResult")
        'transferResult = session.GetFiles("/home/user/*", "d:\download\", False, transferOptions)
        transferResult = session.GetFiles(filename, uploadFolder, False, transferOptions)
        ' Throw on any error
        transferResult.Check()

        ' Print results
        For Each transfer In transferResult.Transfers
            'Console.WriteLine("Download of {0} succeeded", transfer.FileName)
            Wscript.Echo "Download of {0} succeeded" & transfer.FileName
        Next
    End Using

    Return 0
Catch e As Exception
    'Console.WriteLine("Error: {0}", e)
    Wscript.Echo "Error: {0}" & e
    Return 1
End Try




Rename mapped drive with powershell

$
0
0

Hello,

I would like to rename mapped network drives via Powershell.

here is the script i found on the inernet and i have modified it slightly.

param($deviceID = "R:", $name ="NewTest")
$drive = Get-WmiObject "Win32_LogicalDisk WHERE DeviceID = '$DeviceID'"
    if (-not $drive) { return }                      
    $drive.VolumeName = $name
    $null = $drive.Put()
    $Drive.DeviceID



Michael


Using PowerShell to copy specific files to a folder based on text file list

$
0
0

I'm attempting to use PowerShell to copy specific files to a folder based on a text file list of file names. I've been working on this for a long time but have not been successful. What I need to do is copy specific PDF files from a number of folders that also contain files other than PDF files.

The PDF file names can vary in the number characters in their name but they always contain three or four numbers followed by a dash and then two numbers and there can be letters or even words on either sides of the  number sets.

The files are housed in folders named the same as the numbers to the left of the dash in the file names. For instance D2120-05A and  B2120-27E would both be found in the folder named 2120 and C768-39 and C768-92F would both be located in the folder named 768 and so on. 

The text file used by PowerShell to locate the files only contains the numeric portion of the file names. 

EXAMPLE:

6000-60
6000-63
6000-64
6000-66
6000-71
6000-73
6000-74
6000-11
6000-13
6000-17
6000-59

Since the folder names where the files are stored match the digits to the left of the dash in the file names I tried to split those numbers from the filename and append it to the root directory of where the files are stored. So for the file 2120-27 I would split out 2120 and append it to the file path like  "\\fileshare\test\2120\" and then I would append the file name "\\fileshare\test\2120\*2120-27*.pdf" adding wildcards to the beginning and end of file name, to match any possible naming variations, and adding the ".pdf" file extension.

But there is something wrong with the way I'm doing this because I only return the first file and then after that generate the same path over and over and only file names iterate.

Does anyone know what I'm doing wrong?

If I can just figure this part out my next step would be to add a number and dash to the beginning of each file copied so that I can combine the PDFs in Acrobat in the same order as in the file list for my projects. I also plan to generate a text list of any PDFs not found.

Here's the code and the output.

PowerShell script

$source = "\\fileshare\test\"

$destination = "E:\found"

$file_list = Get-Content "E:\filelists\filelist1.txt" 

$var1 = '\*'

$var2 = '*.pdf'

foreach ($file in $file_list)
{

$strSplit = $file.Split('-')

$a = $strSplit[0]

$source = "$source$a$var1$file$var2"

Write-Output ($source)

Copy-Item $source $destination

}

Example of a portion of the output

\\fileshare\test\6000\*6000-60*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf6000\*6000-59*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf6000\*6000-59*.pdf5007\*5007-00*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf6000\*6000-59*.pdf5007\*5007-00*.pdf5007\*5007-07*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf6000\*6000-59*.pdf5007\*5007-00*.pdf5007\*5007-07*.pdf5007\*5007-10*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf6000\*6000-59*.pdf5007\*5007-00*.pdf5007\*5007-07*.pdf5007\*5007-10*.pdf5007\*5007-25*.pdf
\\fileshare\test\6000\*6000-60*.pdf6000\*6000-63*.pdf6000\*6000-64*.pdf6000\*6000-66*.pdf6000\*6000-71*.pdf6000\*6000-73*.pdf6000\*6000-74*.pdf6000\*6000-11*.pdf6000\*6000-13*.pdf6000\*6000-17*.pdf6000\*6000-59*.pdf5007\*5007-00*.pdf5007\*5007-07*.pdf5007\*5007-10*.pdf5007\*5007-25*.pdf5007\*5007-26*.pdf



TFS Build & Release Management

$
0
0

I am trying to write a PowerShell script to:

  1. Kick off a build for a given build definition and get the build number.
  2. Link the build artifact to a given release in release management.

Hoping someone can help!

Thanks!


Tim

Replace date with current date-15 days dynamically in multiple files present in fold

$
0
0

I am completely new to VB scripting and  I am trying to work on a VB script where it is a *(star) delimited file has a multiple lines starts with RTG and 3rd column=TD8  and 
When that line found I want to replace date part with  currentdate minus 15 days which is (20190421) and it should work for all the files present in folder and also the modified content of file should get write back to respective files .

$ cat temp.txt
RTG*888*TD8*20180429~
TWW*888*RD8*20180201-20180201~
RTG*888*D8*20180429-20180601~
KCG*888*TD8*20180201-20180201~
I want the output as below by changing date. Please help. I am looking for VB script to make it work for all files present in that directory

RTG*888*TD8*20190421~
TWW*888*RD8*20180201-20180201~
RTG*888*TD8*20190421-20190421~
KCG*888*TD8*20180201-20180201~

Kindly help me out wih a VB Script. 

Add-AdGroupMember

$
0
0

I've been trying all different variations to add multiple test security groups to my test machines, and whenever I try to do use the identity parameter to point the information to a file, it says the format I've provided is not supported. I've tried creating CSV files and importing, in addition to reading the content of a text file but to avail.

I managed to achieve what I wanted by doing the below, but this is very long winded as it's without variables. What are best practices in terms of bulk adding security groups to multiple machines? This is only five machines, so you can imagine the issues without about fifty doing it like this!

#Enable AD in PowerShell
Import-Module ActiveDirectory

#Creation of Machines

#Define variables to get all required machines
$com1 = Get-ADComputer -Identity "CN=AVTECH-TEST1,OU=Computers,OU=Root,DC=Avtech,DC=Com"
$com2 = Get-ADComputer -Identity "CN=AVTECH-TEST2,OU=Computers,OU=Root,DC=Avtech,DC=Com"
$com3 = Get-ADComputer -Identity "CN=AVTECH-TEST3,OU=Computers,OU=Root,DC=Avtech,DC=Com"
$com4 = Get-ADComputer -Identity "CN=AVTECH-TEST4,OU=Computers,OU=Root,DC=Avtech,DC=Com"
$com5 = Get-ADComputer -Identity "CN=AVTECH-TEST5,OU=Computers,OU=Root,DC=Avtech,DC=Com"

#Define variables to get all required groups
$grp1 = Get-ADGroup -Identity "CN=TESTGROUP1,OU=Groups,OU=Root,DC=Avtech,DC=Com"
$grp2 = Get-ADGroup -Identity "CN=TESTGROUP2,OU=Groups,OU=Root,DC=Avtech,DC=Com"
$grp3 = Get-ADGroup -Identity "CN=TESTGROUP3,OU=Groups,OU=Root,DC=Avtech,DC=Com"
$grp4 = Get-ADGroup -Identity "CN=TESTGROUP4,OU=Groups,OU=Root,DC=Avtech,DC=Com"
$grp5 = Get-ADGroup -Identity "CN=TESTGROUP5,OU=Groups,OU=Root,DC=Avtech,DC=Com"
$join = Get-ADGroup -Identity "CN=JOIN DOMAIN,OU=Groups,OU=Root,DC=Avtech,DC=Com"

#AD Join group to all machines
Add-ADGroupMember -Identity $join -Members $com1
Add-ADGroupMember -Identity $join -Members $com2
Add-ADGroupMember -Identity $join -Members $com3
Add-ADGroupMember -Identity $join -Members $com4
Add-ADGroupMember -Identity $join -Members $com5

#Add all groups to AVTECH-TEST1
Add-ADGroupMember -Identity $grp1 -Members $com1
Add-ADGroupMember -Identity $grp2 -Members $com1
Add-ADGroupMember -Identity $grp3 -Members $com1
Add-ADGroupMember -Identity $grp4 -Members $com1
Add-ADGroupMember -Identity $grp5 -Members $com1

#Add all groups to AVTECH-TEST2
Add-ADGroupMember -Identity $grp1 -Members $com2
Add-ADGroupMember -Identity $grp2 -Members $com2
Add-ADGroupMember -Identity $grp3 -Members $com2
Add-ADGroupMember -Identity $grp4 -Members $com2
Add-ADGroupMember -Identity $grp5 -Members $com2

#Add all groups to AVTECH-TEST3
Add-ADGroupMember -Identity $grp1 -Members $com3
Add-ADGroupMember -Identity $grp2 -Members $com3
Add-ADGroupMember -Identity $grp3 -Members $com3
Add-ADGroupMember -Identity $grp4 -Members $com3
Add-ADGroupMember -Identity $grp5 -Members $com3

#Add all groups to AVTECH-TEST4
Add-ADGroupMember -Identity $grp1 -Members $com4
Add-ADGroupMember -Identity $grp2 -Members $com4
Add-ADGroupMember -Identity $grp3 -Members $com4
Add-ADGroupMember -Identity $grp4 -Members $com4
Add-ADGroupMember -Identity $grp5 -Members $com4

#Add all groups to AVTECH-TEST5
Add-ADGroupMember -Identity $grp1 -Members $com5
Add-ADGroupMember -Identity $grp2 -Members $com5
Add-ADGroupMember -Identity $grp3 -Members $com5
Add-ADGroupMember -Identity $grp4 -Members $com5
Add-ADGroupMember -Identity $grp5 -Members $com5

Powershell Scripting Backup and overwrite files

$
0
0

Greeting, 

I am looking to write a script in powershell in Environment of 50+ servers.

Backup files to different folder and than overwrite the originals ones.

Step 1

Firstly we need to backup these .XML and .config files to its own separate Versioning folder (the folder is already exists on each location)

e.g

\\SERVERNAME\c$\AAA\Mobile\Outbound\Versioning\
\\SERVERNAME\d$\inetpub\WebServices\AMR\Versioning\

Step 2

Overwrite original .XML and .config files  from Source machine(SERVERNAME-X) that has exactly the same folder structure and files name convention.

\\SERVERNAME\c$\AAA\Mobile\Outbound\Outbound.config
\\SERVERNAME\c$\AAA\Mobile\OutboundPW\OutboundPW.exe.config
\\SERVERNAME\c$\AAA\Tasks\DailyProvisioningCheck\DailyProvisionCheck.exe.config
\\SERVERNAME\c$\AAA\Tasks\YIT\App.config
\\SERVERNAME\c$\AAA\Tasks\FIVE\Officore.exe.config
\\SERVERNAME\c$\AAA\Tasks\RS232\Blue.xml
\\SERVERNAME\c$\AAA\Tasks\RS232\Orange.xml
\\SERVERNAME\d$\inetpub\WebServices\AMR\Web.Config
\\SERVERNAME\d$\inetpub\WebServices\Connection\Web.config
\\SERVERNAME\d$\inetpub\WebServices\API\Web.config

I will happy for some direction how to attack it.

thanks heaps
asher

How to automatically tag the creator of a resource

$
0
0
Looking for a json query to automatically tag the creator of a resource on azure

Powershell scripting to create modern site in SharePoint online

$
0
0

Hello,

Any one have powershell script  to create modern sites with the help of Csv in share point online?

I want to create close to 100 sites can any one help me !

Thank you


enumerate web db connection strings.

$
0
0
I was tasked to get website names, path to the folder, and group/users and group members to those websites. I have been able to figure out and get that information however after getting that information it was added that I needed to also get, from what the GUI reports as " Connection String ". From what I can tell it is the information as to what database sources that particular website is using. I have searched for a day now and can't find any examples as to where to look or even what to look for, I hope you can point me in the correct direction where I can get this information. I have even tried to find the information in config files on the server but, I can't find where that info is stored either. I am pretty sure it's somewhere because if you go into the GUI pick a website and the icon that looks like can with a small ab on it it sends you to a list and location of databases that website uses. Any help you can give me will be greatly appreciated. Thanks.

Help ignoring duplicate external email addresses while importing CSV

$
0
0

I'm trying to import a CSV file through power shell.  When the script gets to a duplicate email address, it does not import the contact.  I need to learn how to get my script to ignore duplicate email addresses:

Bob Smith Info@Contoso.com

Fred Jones Info@Contos.com

I need the script to add both of these, however it won't add the second when it sees the email address already exists.  I've searched for what to add to force this but no luck.

Import-Csv .\ContososContacts.csv|%{New-MailContact -Name $_.Name -DisplayName $_.Name -ExternalEmailAddress $_.ExternalEmailAddress -FirstName $_.FirstName -LastName $_.LastName}

Using Get-WinEvent without admin rights - getting error "Get-WinEvent : Attempted to perform an unauthorized operation." if FilterHashTable uses Providername

$
0
0

Hi 

I've been trying to get Get-WinEvent to work without local admin permissions on remote servers.  I can get this to work with the non-admin user in the local "Event Log Readers" group on the remote server, mostly.  The problem I get is when using FilterHastTables with the Providername filter. This results in an error "Get-WinEvent : Attempted to perform an unauthorized operation."

For example I can run:

Get-WinEvent -ComputerName RemoteServer1 -FilterHashTable @{LogName = "Application"} | Where-Object -Property Message -Like "*SMS_WSUS_SYNC_MANAGER*" | Select -First 10

And get the expected events returned and no errors. 

But if I run this:

Get-WinEvent -ComputerName RemoteServer1 -FilterHashTable @{LogName = "Application"; Providername='SMS Server'} | Where-Object -Property Message -Like "*SMS_WSUS_SYNC_MANAGER*" | Select -First 10

I get no events returned and the error "Get-WinEvent : Attempted to perform an unauthorized operation." 

Both work just find if I have local admin rights on the remote server. While the first one works the second one is much faster. 

Is anybody able to explain to me why this happens and how it might be fixed for non-admin users?  


Powershell ISE. Script that creates a VM from template inn the specified Datacenter

$
0
0

I need help solving this error

New-VM : 07.05.2019 14.01.12New-VMTemplate parameter: Could not find any of the objects specified by name.
At C:\Powershell-scripts\Script that creates a VM from template inn the specified Datacenter.ps1:20 char:1
+ New-VM -Name $VMName -Template $VMtemplate -VMHost (get-vmhost)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (VMware.VimAutom...mplate Template:RuntimePropertyInfo) [New-VM], ObnRecordProcessingFailedException
    + FullyQualifiedErrorId : Core_ObnSelector_SetNewParameterValue_ObjectNotFoundCritical,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM

This is the script

# Virtual Center Details
$server_address = "192.168.1.113"
$username = "RødtBord@vsphere.local"
$password = "123"

#TemplateName : Name of the Template which is used for the VM deployment
#VMName  : The Name to be used for the new VM creation
#VMtemplate : specifies what Datacenter the template is located in. And searches for templates whose names start with Martin

$TemplateName = "Martin windows 10"
$VMName = "MWindwos10test"
$VMtemplate = "Get-Template -name Martin* -Datastore 'Host 44'"

#Connecting to the VI Server

Connect-VIServer -server $server_address -User $username -Password $password

#Creates a new vm using a specified template

New-VM -Name $VMName -Template $VMtemplate -VMHost (get-vmhost)

#Starts the VM we just created with the template

Get-VM -Name $VMName | Start-VM

Folder Permissions repair

$
0
0

I have a situation where all folders in our shared network have duplicate permissions. The groups that have inherited permissions were somehow also added directly to each folder. There are hundreds of thousands of folders affected.

Here is an example from one folder

Group Name PermissionInherited
NT AUTHORITY\SYSTEMAllowFullControlFALSE
BUILTIN\AdministratorsAllowFullControlFALSE
CORE\Litigationsec-modifyAllowModify/ SynchronizeFALSE
CORE\AccessManagementAllowFullControlFALSE
NT AUTHORITY\SYSTEMAllowFullControlTRUE
CORE\Litigationsec-modifyAllowModify/ SynchronizeTRUE
CORE\AccessManagementAllowFullControlTRUE
BUILTIN\AdministratorsAllowFullControlTRUE
CORE\FF-Motions_Folder-RWAllowModify/ SynchronizeTRUE

Here is the script I have so far, but it is not working correctly. I am hoping someone will have some ideas where I am going wrong.

$folderspath = "\\Data\Motions\"
$folders = @((get-item $folderspath))
$folders += Get-ChildItem $folderspath -Recurse | where { $_.PSIsContainer -ne $false }

Foreach ($folder in $folders)
{

Write-Host ""

Write-Host "Processing $folder."

Write-Host ""

$acl = Get-Acl -Path $folder.FullName

$accessIdentities = $acl.Access.identityreference

$UniqueIDs = $accessIdentities | select -Unique

$Duplicates = Compare-object –referenceobject $UniqueIDs –differenceobject $accessIdentities

Write-Host "Duplicates found."

Write-Host ""

$dupepermcheck = $DuplicateAccess = $acl.Access | where { $_.identityreference -eq $duplicate}

Write-Host $dupepermcheck

Write-Host ""

Foreach ($dupe in $dupepermcheck){

If ($dupepermcheck[0].filesystemrights -eq $dupepermcheck[1].filesystemrights){

foreach ($duplicate in $Duplicates.inputobject) {

    $DuplicateAccess = $acl.Access | where { $_.identityreference -eq $duplicate -AND $_.isinherited -eq $false}

    $acl.RemoveAccessRule($DuplicateAccess) | out-null

    Write-Host "Modifed rule to remove $duplicateaccess"

}}Else{Write-Host "$duplicate permissions do not match inherited rights."}
Set-Acl -Path $folder.FullName -AclObject $acl
}}

Viewing all 15028 articles
Browse latest View live


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