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

Error Handling Try Catch Powershell

$
0
0

I hope someone can help me here.

I am trying to write a simple script which ask the question if I want to restart a service or a server. I tried using try catch so that when a wrong server OR Service name is given, an error will be displayed.

The try catch part seem not to be working. What I am doing wrong..

#Write-host "Do you want to restart a Servive or a Server?"


$Boolean=Read-host"Type 1 to restart a SERVICE and 2 to restart a SERVER"


if ($Boolean-eq2)

{

   

Get-ADComputer-Filter  {(Name-like"*SAP*")-or(Name-like"*rdsft*") }|Fwname-column2

    $ServerName=Read-Host-prompt"View the list Displayed above and Type in the Server that has to be Restarted"

    try {

             

          Restart-Computer-ComputerName$ServerName-Confirm-Force }

    catch{

           write-host"Server name not correct"-ForegroundColorRed

           

           write-host"This script will Exit"

           
Exit
           }
                                       

           Write-Host"Server is being Restarted"-BackgroundColorGreen

           
Start-Sleep-s10     

               Write-Host"The Connection to this Server will be tested if its back online"-BackgroundColorGreen
          
ping$ServerName-t
        
       }

else

       

    {

        Get-ADComputer-Filter  {(Name-like"*SAP*")-or(Name-like"*rdsft*")}|Fwname-column2

        $ServerName=Read-Host-prompt"View the list of Servers displayed above and Type in the one from which you want" 

            Write-host`n`n

                                                                                                                                        

            Get-service-ComputerName$ServerName                                                                                   

            $ServiceName=Read-Host"Which Service Do You want to Restart, Please give in the Service Name?"

                                                                                                                                                                                                                       
         try {
             
Restart-Service-Name$ServiceName }          

         catch
         
{
               
write-host"Something went wrong"-ForegroundColorRed
               
exit

          }

          Write-host"Service will be restarting..."


          Write-host`n`n


          Start-Sleep-s20


         Write-host" We will check the Event logs to see if the Service actually restarted"-BackgroundColorMagenta


         Get-EventLog-Newest5-LogName"System"

     

      }

   

      


       

       

       


                    

 

       



Powershell Script- remove all security groups from all disabled users and output to text file

$
0
0

Hello 

I am new to powershell , and basically i need a script that can remove security groups from all disabled OUs and then puts out a text file on the desktop after the script has completed, does it exist? 

Kind regards 


difference between local WMI request and "invoke-command" request

$
0
0

Hopefully you can stop me banging my head...

when i run this command, i receive the correct Last Boot Time converted

Get-wmiobject win32_OperatingSystem -computername XXXX| select csname, @{LABEL='LastBootUpTime' ;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} | FT @{l='Server';e={$_.csname}}, LastBootupTime

But if I run the same remotely on the server, the Boot Time is blank. 

Invoke-Command -command {Get-wmiobject win32_OperatingSystem} -computername XXXX | select csname,  @{LABEL='LastBootUpTime' ;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} | FT @{l='Server';e={$_.csname}}, LastBootupTime

If I use just the lastbootuptime, with no conversion or label, the data is received (20160615032402.500000-240)

what am i doing wrong?

thanks

script to read the eventlogs and trigger a mail if found error

$
0
0

Hi,

i need a vb script which can read the application eventlog and search for a specific event content and trigger a mail if found

How to retrieve host of another powershell console

$
0
0

Hi

Is there a way of retrieving the host (System.Management.Automation.Internal.Host.InternalHost) of another powershell.exe process?

I start several powershell processes, for example

$sh = start powershell.exe -PassThru -args .\start-sh.ps1
$dh = start powershell.exe -PassThru -args .\start-dh.ps1

and would like to monitor them from the calling console, checking the buffer of their hosts ($host.GetBufferContents($rect)) for warning and errors. However, I don't know how to obtain the host of these new processes.

I would be grateful for any hints how to achieve (if possible) that.

Select-String Revisited

$
0
0

I've been working on parsing through netstat log files - specifically I'm looking for matches on ports 139 and 445.

Through forum and online investigation I've found code that sort-of works... 

Select-String -Pattern '(10.*:445)|(10.*:139)' "$filename"

However, the issue I run into, is that this not only matches lines with port 445, but also port 4453, 4459 etc... 

Additionally it finds port 139, 1393, 1399 etc...

I was able to wild-card the beginning of the string to only locate IP's with a 10. in the beginning.

Is there a means by which I can limit the matches to "ONLY" 139 and 445?

Office to powershell communication

$
0
0

Good Day,

I'm fairly new to Powershell.

There is lot's of mention about communicating with office products through Powershell.  Is there a way to reverse that communication.   If I have a powerpoint project,  can I click a button on that presentation and call a Powershell function.? I've been searching everywhere to try and figure this out.   

If it's possible could someone post an example with code.  

Thanks

Powershell Parameters with .hta

$
0
0

I have several powershell scripts for common requests from our Access Management and Help Desk teams.  I would like to give these scripts to them, but it just generates a bunch of questions about powershell.  To get around this, I am creating an .hta front end that will allow them to select the actions they want to perform and the scripts will be run in the background.  All actions will be logged centrally and the scripts will be run using a service account to prevent permissions issues.  Each of these scripts requires different parameters and I am trying to avoid creating a separate .hta for each script, but I haven't figured out a way to get around this.  

Am I overthinking this or is there a way to have the powershell script feed the parameters it needs to the .hta so that the user is prompted for the parameters each script needs when called rather than having a separate .hta for each script?

Some examples of the scripts are adding a user to a group, creating a shared mailbox and setting an owner, and creating a distribution group.


How to Start/Stop multiple windows services on multiple machines using arrays in powershell script.

$
0
0

Hi,
This is sathish working as build and release automation developer.

I have a scenario, that i want to write power shell script for the below.

1) Assigning multiple servers and services for an array.
2) Stop the services on the specific servers which we are passing to the array.
3) If files are existing in the path, we should Remove that files and Copy new Files.
4) Start the services which we stopped before.

below is the script...this is working to start/stop services but it's not taking array values...


# Info of Servers
Arrayofservers = Array(server1,server2,server3)
Foreach(Eachserverinfo in Arrayofservers) {
   write-host "\r" $EachserverInfo;

Arrayofservices = Array(Service1,servive2,service3)
Foreach(Eachserviceinfo in Arrayofservices) {
write-host "\r" $EachserviceInfo;

get-service -computername $SvrName -name $services | % {

Write-host "$($_.name) on $SvrName is $($_.status)"
If ($_.status -eq 'running') {
         Write-host "Stopping $($_.name)..."
         Write-host "$($_.name) is stopped"
         $_.Stop() }
         }
else ""

#Copy Deployable Items to the Server
write-host "Copying File: $Env to $BasePath/$Env/"
Copy-Item "$sourcepath"  "$Targetpath" -Force;


Write-host "$($_.name) on $SvrName is $($_.status)"
If ($_.status -eq 'stopped') {     
         Write-host "Starting $($_.name) ..."
         Write-host "$($_.name) is started"
        $_.Start()}
else ""
}

can any one help me out with the script.

Running commands on multiple servers

$
0
0
I need to run following commands on 100+ servers. Is there any easy way to run?

winrm set winrm/config/service/auth @{Basic="false"}
winrm set winrm/config/service @{AllowUnencrypted="true"}
winrm set winrm/config/service/auth @{Negotiate="true"}

System.Collections.ArrayList .contains method

$
0
0

I'm trying to create an everyone but, these people group using PowerShell.

$Users=[System.Collections.ArrayList]@()

$DeniedUsers=[system.Collections.ArrayList](Get-ADGroupMember"ADSecGroup"
| Select DistinguishedName)

Get-ADUser
-Filter*-SearchBase"OU=USERS,DC=CORP,DC=COM" | SelectDistinguishedName
|ForEach-Object{$null=$Users.add($_)}

I want a new collection that contains everyone in$Usersexcept those in$DeniedUsers. I've been trying things like this without any success.

$AllowedUsers=$Users| Where-Object{!$_.Contains($DeniedUsers.DistinguishedName)}


 


Robert W. Kirchhof






How to change DNS remotely depending on the subnet

$
0
0

Hello

I'm looking for a way to automate with powershell the DNS update of my client computers and servers (in Windows 7 and 2012) depending on their subnet. The main idea is to set differents DNS depending on the client subnet.

I started a script with what i have found on different forums but it does not evaluate the first condition (IF) and i didn't find what is the root cause :

$Computerlist = get-content "C:\list\servers.txt"
$dnsserversSite1 =@(192.168.1.253,192.168.1.254)
$cred = get-credential Domain\username

foreach ($computername in $computerlist) {
    $ping =  (Test-Connection -comp $computerlist -Count 1).ipv4address.ipaddressToString
    if ($ping.ipv4address.ipaddressToString -like '^192.168.1$|^192.168.2$'){
        $remoteNic = Get-WMIObject Win32_NetworkAdapterConfiguration -credential $cred -computername $computerlist |where{$_.NetEnabled -eq 'True'}
        $index = $remotenic.index
        $DNSlist = $(get-wmiobject win32_networkadapterconfiguration -credential $cred -computer $computername -Filter ‘netenabled=true’ | where-object {$_.index -eq $index}).dnsserversearchorder
        $priDNS = $DNSlist | select-object -first 1
        Write-host "Changing DNS IP's on $computername" -b "Green" -foregroundcolor "white"
        $change = get-wmiobject win32_networkadapterconfiguration -credential $cred -computer $computername | where-object {$_.index -eq $index}
        $change.SetDNSServerSearchOrder($DNSserversSite1) | out-null
        $changes = $(get-wmiobject win32_networkadapterconfiguration -credential $cred -computer $computername -Filter ‘netenabled=true’ | where-object {$_.index -eq $index}).dnsserversearchorder
        Write-host "$computername's Nic1 Dns IPs $changes"
    }
    else {
        Write-host "$Computername is down cannot change DNS address" -b "Red" -foregroundcolor "white"
    }
}

Your help is really welcome and appreciate.

Thank you in advance

VB download the Windows Update KB specified and install it

$
0
0

Hello Scripting Guys..I need some help.

I have an array of KB and I want to check if my PC has this KB installed or not. If it has not installed, I want the script to download the KB and install the KB without restarting the PC or ask me to confirm. I have prepared the following script which identify whether a KB is already installed or not. I am still missing the part where it download and install the KB.

Thank you so much!

'Enter the name of the computer to check:
ComputerName = "."    'Replace the dot with a computer name, to connect to a remote computer

 Dim myArray(4)
 myArray(0) = "3163017" ' KB3163017
 myArray(1) = "3163018"
 myArray(2) = "3163019"

 for i = 0 to 2
	status = CheckParticularHotfix(ComputerName, myArray(i))
	If status = true then
		wscript.Echo "The hotfix with number "  & myArray(i) & " IS installed."
	Elseif status = false Then
		wscript.Echo "The hotfix with number "  & myArray(i) & " is NOT installed."
		'To Do:
		'Download the KB and Install it without human inteference and prevent restart untill all system update is completed
	else
		wscript.Echo "Error, unable to check for hotfix. Error is: " & status
	end if
 Next
private Function CheckParticularHotfix(strPuter, strHotfixID)
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Version 1.0
    ' Checks if a particular hotfix is installed or not.
    ' This function has these 3 return options:
    ' TRUE, FALSE, <error description>
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    On error resume next
    Set objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & strPuter & "\root\cimv2")
    if err.number <> 0 then
        CheckParticularHotfix = "WMI could not connect to computer '" & strPuter & "'"
        exit function 'No reason to continue
    end if

    strWMIforesp = "Select * from Win32_QuickFixEngineering where HotFixID = 'Q" & strHotfixID &_"' OR HotFixID = 'KB" & strHotfixID & "'"
    Set colQuickFixes = objWMIService.ExecQuery (strWMIforesp)
    if err.number <> 0 Then    'if an error occurs
        CheckParticularHotfix = "Unable to get WMI hotfix info"
    else 'Error number 0 meaning no error occured
        tal = colQuickFixes.count
        if tal > 0 then
            CheckParticularHotfix = True    'HF installed
        else
            CheckParticularHotfix = False    'HF not installed
        end If
    end if
    Set colQuickFixes = Nothing

    Err.Clear
    On Error GoTo 0
end function 

Have Script Need Help

$
0
0

Currently I have a script that will pull the Profile Image Path to get a list of all profiles on a machine. What I am trying to do is to alter the output to get rid of everything but the actual profile name. Here is the script so far. 

$path = 'Registry::HKey_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\*'
$items = Get-ItemProperty -path $path
Foreach ($item in $items) {
    $objUser = New-Object System.Security.Principal.SecurityIdentifier($item.PSChildName)
    $objName = $objUser.Translate([System.Security.Principal.NTAccount])
    $item.PSChildName = $objName.value
}
echo $items | Select-Object -Property ProfileImagePath

I have tried everything I could think of so any help would be greatly appreciated. Thanks!

Script to restrict remote login for new users

$
0
0
Hi Experts, I just want to restrict remote logins only if that particular user profile is not present already. This restriction should not impact existing profiles which exists in c:\users\<Existingprofiles>, i.e existing users should able to do remote login.  Simply my intention is profiles should created only in Interactive logins, Once profiles created then we can allow RDP/remote to those profiles.

Yuvarasan Sothi


Tool Strip Menu Item

$
0
0

Im adding successfully values to a dynamic object ToolStripMenuItem. but when I create an associate event ON_Click $data $EventArgs I notice if I call the eventwith any of the values, ToolStripMrnuItem it will contain the last value use in the definition statement of event.

 $MenuBar = New-Object System.Windows.Forms.MenuStrip
     $Form.Controls.Add($MenuBar)    
    $UserGMenu = New-Object System.Windows.Forms.ToolStripMenuItem
    $UserGMenu.Text = "&Group Users"
 
    ForEach($GroupUser in $global:DropDownGUsersArray)
    {
      $GroupValue = New-Object System.Windows.Forms.ToolStripMenuItem
      $GroupValue.Text = $GroupUser     
      $UserGMenu.DropDownItems.Add($GroupValue)
      $GroupValue.Add_Click( { OnClick_GroupUser $GroupUser $EventArgs} ) ----  This instruction does not work as expected will hold the last value assign to $GroupUser from the collection regardless which one I select from the menu.  
    }

How can I assure the values are assign to the event I want to call?


michael john ocasio


Hot to get the ID of the hotfix

$
0
0

I want to search for Windows Update and I want it to return me the ID of the HotFix (eg. KBxxxxxxx). I have the following code and it throw me error when I call "update.HotFixID". How do I get the HotFixID? I don't want the full name. Thanks

Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()

WScript.Echo "Searching for updates..." & vbCRLF

Set searchResult = _
updateSearcher.Search("IsInstalled=0 and Type='Software'")

WScript.Echo "List of applicable items on the machine:"

For I = 0 To searchResult.Updates.Count-1
    Set update = searchResult.Updates.Item(I)
    WScript.Echo I + 1 & "> " & update.HotfixID ' this line return error saying "Object doesn't support this property or method: 'update.HotfixID'"
Next

Query depending on number of variables from file.

$
0
0

I know there is an easy answer for this but it seems to be just out of grasp.  I am working on PowerShell script to query remote machines for service information and then restart is required, we have some SQL instances being notty.  The checks come from a text file that looks like the following:

AJBSRV-AD:NTDS
AJBSRV-SQL:MSSQLSERVER,W32Time

So the first part is the server name and the second are the services to query on.  Now I don't want multiple queries going to the same machine I wanted to use a Select-Object Where and then use an or for each service.  My issue is how do I code out the command to work with a single service or for instance 10 different ones?  I am trying to keep the code clean and working properly.  I know I could work out some deal where I build the command by adding to a single variable over and over until I have no more variables then making the final call using the built up variable but this seems sloppy.  Any suggestions?

Thanks

TextBox or Popup using a script

$
0
0

I am looking for a Textbox or a popup, which should remain when the user logs in. Its kind of a message that we need to make it aware for particular set of users. Can we get a script created for this or guide me out. User shouldn't be allowed to close this. It should infact remain on top of wallpaper on the right hand corner.

Any guidance will be greatly appreciated.

How to determine which local groups a user account is a member

$
0
0

Hi,

I have a utility local user account that must remain as a standard user (no local group memberships). I need a script that will run daily that inspects if the user account belongs to any local groups and then remove it from those groups leaving it as a standard user. Let me be clear that I am talking about local groups on a client computer, not Active Directory.

I have done some searching but it is looking like there is very little information on this topic. There are plenty of examples of handling Active Directory. I'm not asking anyone to write code for me but if you could get me on the right track, I can research the rest.


Thanks,
Rob
Viewing all 15028 articles
Browse latest View live


Latest Images

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