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

Powershell - Daily Health Check

$
0
0

Hi all,

I have a number of different w8k and w12k servers in different sites and I wanted create a daily health check to check services are up. For instance I can write a ps script to check run at 6am daily and check various services on a windows server and then generate a html report and mail it to a distribution list. However on some of my servers I only have one service that needs to be checked I wanted a was to check the services and collate all the reports into one place and output just one html report?

So for example could I output the results to a text file, run an ftp job to send the result to a central location and then run a ps to scrap all the results and output to html, or could the text files be scrapped from an email, this method makes better sense for me as some of these servers will have ACLs between then and getting send via smtp will be easier then ftp.

Would like to know if anyone has any ideas or experience with doing something like this?


Send emails from a csv file (grouping records with the same email addresses)

$
0
0

Writing a script to send emails from a csv which contains record details and email addresses using the Send-Mailmessage cmdlet.

That part is no trouble, however, the csv file contain records that can have the same email address.

Is there a way/method I could send the records with the same email address once instead of sending individual email messages?

Thanks

****************

Data in the csv file

Record number, description, email

1234, Test 1, test@hotmail.com

5678, Test 2, kalam@hotmail.com

1245, Test 3, test@hotmail.com

4578, Test 4, test@hotmail.com

$data = Import-csv c:\records.csv

ForEach($address in $data)
{
 Send-mailmessage  -To $address.emails -from test@hotmail.com -subject "List of records" -Body $data -SmtpServer 192.168.1.1
}


Need PS Script

$
0
0

Hello Friends..I am new to PS.. Need PS Script to add the Users into Folder Permission.

Example :Like C:\Windows needs to have BUILTIN\Users - Allow Read(This Folder Only), Everyone - Allow Read(This Folder Only), CREATOR OWNER - (InheritOnly)Allow Full Control(Subfolders and files only), SYSTEM : Modify(this folder only).

For Windows Server 2012 R2 : BUILTIN\Users -Rear & Execute(This folder, subfolders and files), BUILTIN\Administrators- Modify(This Folder Only)..

Thanks for the Help

Cmdlet - Display most recently modified documents, installed applications, and modified registry keys?

$
0
0

Hello,

I'm currently trying to figure out how to go about displaying the most recently installed application on a local host? I was thinking a real simplified version would be to Dir a directory then compare and format the last right time appropriately but I noticed parent directories do not reflect the modifications in their subdirectory. For example, from C:\ the last modification was yesterday, even though I drill into C:\Users\Username\ and I can see I've changed a number of files within the last 10 minutes.

I'm thinking my logical concept is off in some way - or maybe there is a cmdlet out there I'm not aware of that will make this easier. I assume the flow will go something like > Pull all contents of drive > list in most recently modified order first> -newest 10.

First I want to apply this to installations but I would eventually like to extend it to displays most recently modified registry keys as well.

Any and all advice is greatly appreciated in advance!

Thanks!

Can a VBS file edit itself?

$
0
0

Hi guys,

I've searched for the above and all I can find are people wanting to hack their global IT policy.

In a nutshell, I've written a login script using VBS. The username and password therefore either have to be saved in the file itself, or input using an inputbox in plain text.

I've personally opted for a combination, so my loginId is saved in the VBS file, my password is partially saved and I am only prompted for a "password number". So for example, if my username was "jeffsimply" and password was "password1a". I would most likely increment my password for the relevant system so that next month when asked for a new password I would choose "password 2a" and so on.

What I would like to work toward, is a script with various usernames and passwords, with the ability to update the usernames and or passwords without needing to edit the script. I don't know the syntax if it's even possible but it would be something like

If booFirst = 1 Then
Clear Line 5
Set Line 5: strUser = "jeffsimpler"
booFirst = 0
Else
End If

So that the first time the code is run, the strUser is set (I would most likely implement this with an inputbox and a further input box to confirm before setting the first time run check to false.

Any help would be grand!

This is my current code:

Dim ObjectIE Set ObjectIE = CreateObject("InternetExplorer.Application") ObjectIE.Navigate("www.loginpage.com") strUser = "jeffsimply" strPasswordPre = "password" strPasswordPost = "a" Title = "Password number" message = "Please input password number and click ok" Default = "" Question = Inputbox(message,title,Default) strPassword = Question ObjectIE.visible = True Wait objectIE, 500 set doc = ObjectIE.document doc.getelementbyID("txtUser").value = strUser doc.getelementbyID("txtPassword").value = strPasswordPre & strPassword & strPasswordPost doc.getelementbyID("butLogin").click Sub Wait(ObjectIE, SleepInterval) Do WScript.Sleep SleepInterval Loop While ObjectIE.ReadyState < 4 And ObjectIE.Busy End

Use the %UserProfile% variable within a VBscript

$
0
0

I am currently working on a VBscript that will delete any files with a "Modify date" of older than 90 days. I am able to get the script to work correctly if I use the absolute path ("C:\<Username>\OneDrive for Business") however when I try to use the %Useprofile% to make the path relative the script fails. I have done some research no delacing Windows Variables however I'm not a scripting expect and am a little confused. Here is the current script that I am using without trying to use the Windows variable:

Const strPath = "c:\KCraig\OneDrive for Business"
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")

Call Search (strPath)
WScript.Echo"Done."

Sub Search(str)
Dim objFolder, objSubFolder, objFile
Set objFolder = objFSO.GetFolder(str)
For Each objFile In objFolder.Files
If objFile.DateLastModified < (Now() - 90) Then
objFile.Delete(True)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Search(objSubFolder.Path)
' Files have been deleted, now see if
' the folder is empty.
If (objSubFolder.Files.Count = 0) Then
objSubFolder.Delete True
End If
Next
End Sub

________________________________

Based on a little research I believe I should add this piece to the script (see below). However when I do the script is stall unable to recognize the %userprofile% variable. Any assistance or tips would be greatly appreciated. Thank You. 

Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")

Help with script to team NICs and assign IP in Win7 SP1

$
0
0

Hi All,

I have the following Power Shell script to team 2 NICs and assign IP, Gateway and DNS server:

# Create TEAM1, by binding 'Ethernet' and 'Ethernet 2' NICs.

New-NetLbfoTeam -Name TEAM1 -TeamMembers "LAN #1","LAN #2" -TeamingMode SwitchIndependent -LoadBalancingAlgorithm Dynamic -Confirm:$false

# 20 second pause to allow TEAM1 to form and come online.

Start-Sleep -s 20

# Configure static IP Address, Subnet, Default Gateway, DNS Server IPs to newly formed TEAM1 interface.

New-NetIPAddress –InterfaceAlias "TEAM1" –IPAddress 10.221.27.32 –PrefixLength 24 -DefaultGateway 10.221.27.1
Set-DnsClientServerAddress -InterfaceAlias “TEAM1” -ServerAddresses 10.221.103.1 

I am trying to run the script in Windows 7 but I am getting the error that the cmdlets do not exist.  I fear that this is not possible to do with PS in Win7.  Is there a way to use PS in Win7 to accomplish this?

If not, can this be done in Win7 with any other scripting language?  I have done some research but haven't had any luck.

Thanks in advance for any help.

Kind regards,

Ken



[PowerShell] Retry with elevated credentials

$
0
0

I have several scripts where I attempt something in a Try{} block.  I catch various Access Denied exceptions in the Catch{} block.  In the Catch{} block, I first prompt for alternate credentials and then retry the same command again but with the addition of the -Credential parameter.  For example:

Try
{
    Remove-ADGroupMember -Identity $Group -Members $Members -Confirm:$false -ErrorAction Stop
}
Catch [Microsoft.ActiveDirectory.Management.ADException]
{
    If ($Credentials -eq $null)
    {
        Write-Warning 'Access rights for the current session are insufficent. Please enter credentials that have access to modify group membership.'
        $Credentials = Get-Credential $null
    }

    Remove-ADGroupMember -Identity $Group -Members $Members -Confirm:$false -Credential $Credentials
}


This creates problems for script maintenance and bug fixing as I have to modify the same code twice in two different places.  I'd much rather do something like this (fake script):

Function Remove-FromGroup($Group,$Members,$Credentials)
{
    Remove-ADGroupMember -Identity $Group -Members $Members -Confirm:$false -Credential $Credentials
}

# Get the current user session credentials and store them in a variable.
$Credentials = Get-CurrentUserSessionCredential

Try
{
    Remove-FromGroup $Group $Members $Credentials
}
Catch [Microsoft.ActiveDirectory.Management.ADException]
{
    Write-Warning 'Access rights for the current session are insufficent. Please enter credentials that have access to modify group membership.'

    # Prompt the user to enter different credentials.
    $Credentials = Get-Credential $null

    Remove-FromGroup $Group $Members $Credentials
}

In this case, the actual code to remove users from a group only has to be maintained in a single place: the Remove-FromGroup function; however, it assumes there is a way to set the Credential parameter to the current user's PowerShell session credentials without prompting them.  In my example I am doing that by setting the $Credentials variable with a mythical Get-CurrentUserSessionCredential cmdlet.

Is there is some method of doing what I'm looking for?  It doesn't have to be the logic like I have above. I'm just looking for some way to try to do something and if it doesn't work due to Access Denied, prompt for different credentials and try the same thing again with the other credentials, but only have the code for the thing to try written once.  Thanks.





Copy files from CSV to existing Excel in Powershell

$
0
0

I have a CSV file with some data. For example:

         CSV                ------>            EXCEL
    Name,Address,Phone                  Name,Address,Phone
    Nick,aaa,9990008989                 Nick,aaa,NULL
    Josh,bbb,8889990909                 Josh,bbb,NULL

I would like to copy each phone number to that specific name from my csv file to the excel one. How would that be possible in powershell? Thank you

Script to Find latest Modify date, and email alert if last modify is older than 4hrs or so

$
0
0

So, I want to monitor a directory, and get an alert if any file in the directory was not modified in the last, 4 hours or so.  

I think I'm on the right track, but I'm missing some pieces here.  Any suggestions?

Here's what I got so far:

::Set time and date to use later if needed
set currentTime_Date=%time% %date%
::For loop to pull the last file (I can't seem to pull the last modify time/date with it... this is where I need a hand)
FOR /F "delims=" %a IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%a 

::Email latest file using blat
blat.exe -to my@email.com -server server@domain.com -f from@email.com -subject "File Checker" -body "test" -attach %NewestFile%(Not sure if I can use the variable for my newest file here or not)


Any suggestions?


Create Shortcut In My Network Places Using PowerShell

$
0
0
Hello!  How can one create a shortcut in My Network Places using PowerShell? I found a method described using VB at http://blogs.technet.com/heyscriptingguy/archive/2005/05/09/how-can-i-create-a-shortcut-in-my-network-places.aspx, but it does not create the shortcut in the same way that the native Windows GUI creates it.  Unfortunately, Group Policy Preferences does not help either since it does not create a proper shortcut in the NetHood folder (it simply creates a shortcut instead of creating a folder with target.lnk and desktop.ini). 

I found another VB solution at http://bartdesmet.net/blogs/bart/archive/2005/09/23/3554.aspx that does correctly create the network location the same way the native Windows GUI does. Is there an easier method to accomplish this using PowerShell?

Thanks.

PowerShell -> change NIC adapter binding order?

$
0
0

Windows 7 x86/x64 (PowerShell or VBScript)

Looking for a script that can change the network adapter binding order. Ideally, this will run immediately after sysprep, with no user interaction.  Would anyone know of a good method?

Account locked after using get_wmi commands

$
0
0

Hi

I am writing some scripts using powershell to get information about servers such as cpu's, memeory etc.

I run the scripts from  a jump server that has access to most of the servers. I logon to the server using a password that lives for 4 hours. The scripts work great however now my ID is getting locked out constantly so I am thinking that the remote connection from the jump server used my credentials at that time and something on the remote computer that is still using that expiredID/PW combo. Is there anyway to connect to servers and not leave expired credentials or running sessions that will cause issues like this.

I read a text file in and loop on several wmi commands like the following

$Computer_info = Get-WmiObject Win32_ComputerSystem -comp $svr

How to change sharing Permission of a folder using powershell

$
0
0

Hi Team,

I have a windows server 2008 R2 File Server.

1. I want to create a share folder on this remote File server for number of users

2. I Also want to give SHARE PERMISSION to respect Users on their Respective folders

How do I set SHARE PERMISSION of a remote file server folder ?

I was using SET_ACL but it set the permission for Security TAB.

Thanks

Restricting Concurrent Logons

$
0
0

HI guys

I have a query . i just want to know is there a script where user can logon to a said domain one at a time

note this is windows server 2008

kindly help .


the devil


Invoke-Command - SQL collation change function

$
0
0

Hi,

I am creating a script to automatically configure SQL servers in Azure from one of the base Azure SQL VM templates. All of my code works well besides changing the default collation of the instance. The PowerShell code works but the problem is that the command only runs the setup.exe command correctly if I have an open RDP session to the server. I'm trying to figure out why it won't run without the RDP session and either work around it or change the code to something that will work consistently. For now, I have it open an RDP session but this method won't work in future when I fully automate the scripts.

Here is my code for the ChangeCollation function:

FUNCTION ChangeCollation
{
    param
    (
    [Parameter(Mandatory=$true)]$DeploymentName,
    [Parameter(Mandatory=$true)]$AdminName,
    [Parameter(Mandatory=$true)]$AdminPassword,
    [Parameter(Mandatory=$true)]$Collation
    )
    Write-Host ("Rebuilding instance collation, setting to $Collation ... ") -ForegroundColor Green

    $setup = (Start-Process -FilePath "C:\SQLServer_12.0_Full\Setup.exe" -ArgumentList "/QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=$DeploymentName\$AdminName /SAPWD=$AdminPassword /SQLCOLLATION=$Collation" -NoNewWindow -Wait -PassThru).ExitCode
            If ($setup -eq 0) { Write-Host ("Successfully set collation to $Collation") -ForegroundColor Green}
            If ($setup -ne 0) { Write-Host ("Failed to set collation to $Collation") -ForegroundColor Red}
}

I execute it as follows, its in a basic retry loop which tries restarting the services or server if the command fails:

try { Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock ${function:ChangeCollation} -ArgumentList $DeploymentName, $AdminName, $AdminPassword, $Collation $NewCollation = Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock {Invoke-SQLCmd "SELECT CONVERT (varchar, SERVERPROPERTY('collation'));"} $NewCollation = $NewCollation.Column1 If ($Collation -ne $NewCollation) { Throw "Collation not changed exception!" } $Stoploop = $true }

Catch

{

.......

}

If I have an RDP session open as the local admin which is the same account as I am running the invoke-command with, the setup.exe runs through just fine. Without an RDP session, Invoke waits a minute or two then exits. I can see from the logs on the server it hasn't tried to change the collation of the instance.

I've tried additional switches on the start-process, like -LoadUserProfile or without -nonewwindow but they made no difference. I have also tried changing the collation with the command sqlservr, seems to work sometimes but its inconsistent and I don't get the returned result saying that it completed successfully so the code just hangs even after the change.

Does anyone have any idea why an exe wouldn't work via an invoke without the RDP session? Or alternatively a better way to change the collation of the database which is consistent?




Getting license status for the servers remotely

$
0
0

We have an environment with different domains and forests with and without trusts.

I need to manage the license for these with out KVM.

I want to findout the servers which are running without activated or with Grace period.

I have been trying with differnt scripts from WMIC and Powershell. But, not able to generate with clear and clean.

Below are the scripts tried. Need assistance on this.

From WMIC

WMIC /Output:@D:\output.txt /node:@D:\serverslist.txt PATH SoftwareLicensingProduct WHERE "ProductKeyID like '%-%' AND Description like '%Windows%'" get LicenseStatus

From Powershell

PS C:\Windows\system32> Get-CimInstance -ClassName SoftwareLicensingProduct |where PartialProductKey |select PScomputern
ame,LicenseStatus

Need help to generate a table with computer name/IP  and  License status.

Thanks in advance.


ndraj

Add a hashtable to another hashtable

$
0
0
########################################################################################################################
Function HDD_Information($Output)
{
    $Server = $Output.Server
    $Output1 = @{};
    $HDDInfor = gwmi win32_diskdrive -ComputerName $Server -EA stop
    Foreach ($HDD in $HDDInfor)
    {
       $Output."Size" = $HDD.Size
       $Output."Model" = $HDD.Model
       $Output1.Add($Output)
    }
    return $Output1

I am trying to add a hashtable to another hastable, but i get an error  :- 

Cannot find an overload for "Add" and the argument count: "1"

+                 $Output1.Add <<<< ($Output)
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

First Hashtable = $Output 

The $Output variable contains the follwing values

@{Model=VMware Virtual disk SCSI Disk Device; Size=12231242555}

@{Model=VMware Virtual disk SCSI Disk Device; Size=84853845435546}

Second Hashtable = $Output1

So When the function returns 2 values, the script enters only one value in the csv file.. I want to save both the values in a hashtable and enter into the csv. Have got the csv part all figured out, just having problem adding both the return values in CSV.

Any help is appreciated!

Harddisk infromation

$
0
0

I need to get the following information about a Harddisk :_

1. UsedSpace

2. The Disktype (Basic or Dynamic)

I am using powershell 2.0 version, and just not getting the above informations.

It appears that the "win32_diskdrive" doesn't have these two parameters. How can i get the "UseDSpace and DiskType" ? ?

VBS - SQL Query

$
0
0

Hello and sorry for my bad English,

I had a problem with a .VBS Script

the function of this script is, that is create a "User" on the SQL Server and in the database


Const adUseClient = 3
Dim cn
Set cn = CreateObject("ADODB.Connection")

dim sql
sql = "USE [master] " & _"GO " & _"CREATE LOGIN [Domain\m2t3_test] FROM WINDOWS WITH DEFAULT_DATABASE=[master] " & _"GO " & _"USE [SL_Daten]" & _"GO " & _"CREATE USER [Domain\m2t3_test] FOR LOGIN [Domain\m2t3_test] " & _"GO " & _"USE [SL_Daten] " & _"GO " & _"EXEC sp_addrolemember N'db_datareader', N'Domain\m2t3_test' " & _"GO " & _"USE [SL_Daten] " & _"GO " & _"EXEC sp_addrolemember N'db_datawriter', N'Domain\m2t3_test' " & _"GO " & _"USE [SL_Log_Daten] " & _"GO " & _"CREATE USER [Domain\m2t3_test] FOR LOGIN [Domain\m2t3_test] " & _"GO " & _"USE [SL_Log_Daten] " & _"GO " & _"EXEC sp_addrolemember N'db_datareader', N'Domain\m2t3_test' " & _"GO " & _"USE [SL_Log_Daten] " & _"GO " & _"EXEC sp_addrolemember N'db_datawriter', N'DOMAIN\m2t3_test' " & _"GO"


with cn
    .CursorLocation = adUseClient
    .Open "Driver={SQL Server};Server=SQLSERVER\SLSQL; Database=master; UID=AA; PWD=AA"
    .CommandTimeout = 0
    .Execute(sql)
end with

cn.close
set cn = Nothing

If i start the Script, i get a Error on Line 40

Synatax Error near the 'GO'.


How i can converte the SQL Query to VBScript?


thx for your Help!



Freundliche Grüsse

Viewing all 15028 articles
Browse latest View live


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