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

Powershell Date and Echo

$
0
0

Hello,

I am trying to echo the date to a file so i can basically just record the last day the script was ran.  I do not what the exact time, but just i am happy with dates.

Anyways i simply do this:

$DATE = get-date -DisplayHint date

echo $DATE >> backupdate.txt

However when looking at the file it outputs a blank line before and 3 blank lines after. I simply want the script to write the date on a new line.  so the 3 blank lines afterwards is a bit excessive.  So i just want this in the file

Monday, February 10, 2014
Monday, February 11, 2014
Monday, February 12, 2014

How can i fix this formatting issue? 



Event Logs Formatting

$
0
0

Hello Everyone,

kindly assist on how i can format information from this powershell command to only get specific information. i.e

Let say i wanted to only output

Caller Computer Name and on a Separate line output Account Name


wevtutil qe Security "/q:*[System[(EventID=4740)]]" /f:text /rd:true /c:1 | Out-String
Event[0]:
  Log Name: Security
  Source: Microsoft-Windows-Security-Auditing
  Date: 2014-02-10T19:08:02.234
  Event ID: 4740
  Task: User Account Management
  Level: Information
  Opcode: Info
  Keyword: Audit Success
  User: N/A
  User Name: N/A
  Computer: ADSVR.CONTOSO.COM
  Description: 
A user account was locked out.

Subject:
	Security ID:		S-1-5-18
	Account Name:		ADSVR$
	Account Domain:		CONTOSO
	Logon ID:		0x3e7

Account That Was Locked Out:
	Security ID:		S-1-5-21-1614895754-926492609-725345543-16381
	Account Name:		Joseph.K

Additional Information:
	Caller Computer Name:	CLIENT002





Meshack

Find and replace string in a file using batch script

$
0
0

I am writing a batch script to replace " ", with " ". The below code works but it prefixes each line with the line number and :.

It is the last part of the line that I am trying to replace.

E.g.

"                    ","BALANCE_SHEET       ","ASSETS              ","03","LEVEL_2   ",Asset Accounts,"                              ",


To be replaced as

"                    ","BALANCE_SHEET       ","ASSETS              ","03","LEVEL_2   ",Asset Accounts,"                              "


Code:

@echo off &setlocal
set "search="                              ","
set "replace="                              ""
set "textfile=Build_Accounts_Plan_Source.txt"
set "newfile=Build_Accounts_Plan_Source_new.txt"

(for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"
type "%newfile%"


Output:

3:"                    ","BALANCE_SHEET       ","ASSETS              ","03","LEVEL_2   ",Asset Accounts,"                              "


Regards,

Ragav.


DSC xWebsite doesn't work properly in Windows Server 2008 R2 SP1 because of Get-Website cmdlet

$
0
0

I'm trying to use DSC to create a new web site using a configuration similar to http://gallery.technet.microsoft.com/scriptcenter/xWebAdministration-Module-3c8bb6be. What I found is if the web site doesn't exist the xWebsite resource fails because Get-Website cmdlet even if filtered by -Name seems to ignore the filter and return something. To fix this problem I had to customize the xWebsite resource and changedGet-Website $Name to Get-Item -Path "IIS:\Sites\$Name" at least in a couple of places (Test-TargetResource and Set-TargetResource).

I hope this behavior is fixed in a next version of the Get-Website cmdlet or otherwise the workaround is implemented at the xWebsite resource.

New_ADUser script

$
0
0

Hi

I have written a script to add new ad users from a csv file and after a few tries now have it working. I'm also trying to add these users to groups in the same way. My csv file contains a column called group and the required groups are added in the format of "Group,Group2,Group3". The code is below:

Import-Csv -Path UserAccounts.csv | ForEach-Object {
$SAM = $_.user
$Group = $_.group
$Groups = $Group.split(",")
foreach($l in $groups){
Add-ADGroupMember -Identity $l -Member $SAM
}
}

When this runs it adds users to any groups that have a scope of Universal, but errors with Global or Domain Local with"ADGroupMember : Cannot find an object with identity: '"Group' under: 'DC=domain,DC=com'."

I'm not sure what I need to change? If I run add-adgroupmember from the cmd line it works for any group.

Thanks.

HOW TO USE GMAIL TO SEND MESSAGES FROM COMMAND PROMPT?

$
0
0
HAY MICROSOFTY,
I HAVE A QUESTION.
I DISCOVERED WERY USEFULL COMMAND IN COMMAND.COM
IT IS
POWERSHELL -COMMAND -SEND-MAILMESSAGE
I WANT TO WRITE A BATCH PROGRAM (WHICH CONTAINS MIXED CMD AND POWERSHELL CODE) WHICH WILL SEND ME AN E-MAIL MESSAGE WHENEVER SOMEONE STARTS WINDOWS ON MY COMPUTER.
BUT, I USE GMAIL ACCOUNT, AND IT LOOKS LIKE IT DOES NOT WORK WITH IT.
I TRIED THIS SCRIPT TO SEND A TEST MESSAGE AND IT DID NOT WORK:
INSIDE TEST.BAT:
@ECHO OFF
ECHO:SENDING TEST MAIL...
POWERSHELL -COMMAND SEND-MAILMESSAGE -TO "SYOBSYOT@GMAIL.COM" -FROM "SYOBSYOT@GMAIL.COM" -SUBJECT "TEST" -BODY "TESTING E-MAIL AUTOMATED SCRIPT" -SMTPSERVER "MAIL.GOOGLE.COM"
ECHO:FINISHED ATEMPTING TO SEND.
EXIT
BUT, THIS SCRIPT FAILS WITH THE FOLLOWING OUTPUT:
SENDING TEST MAIL...
Send-MailMessage : Unable to connect to the remote server
At line:1 char:17
+ SEND-MAILMESSAGE <<<<  -TO "SYOBSYOT@GMAIL.COM" -from "SYOBSYOT@GMAIL.COM" -subject "TEST" -BODY "TESTING E-MAIL AUTOMATED SCRIPT" -SMTPSERVER "MAIL.GOOGLE.COM"
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
FINISHED ATEMPTING TO SEND.
I THINK THAT IT MIGHT BE BECAUSE GMAL REQUIRES USERNAME AND PASSWORD.
BUT, HOW TO SPECIFY IT IN THIS COMMAND?
AND, I THINK THAT IF THERE IS SOME ANONYMOUS SMTP SERVER THAT IT WOULD WORK WITHOUT USERNAME AND PASSWORD.
SO, DO YOU KNOW HOW TO FIX THIS, SO MY SCRIPTS CAN SEND E-MAILS FROM GMAIL FOR ME?
OR, IF IT CAN NOT BE DONE, WILL IT WORK WITH ANONYMOUS SMTP SERVER, AND IF IT WILL, HOW TO MODIFY THIS CODE TO USE IT WITH THAT SERVER?
ANY CODE MODIFICATIONS ARE WELCOME WITH THE ANSWER.
THANK YOU,
SYOB SYOT ♥
(BTW, I AM USING WINDOWS SERVER 2008 WITH POWERSHELL 2.0 AND CMD)

Trying to get this to work: "Move and Disable inactive computer accounts from Active Directory"

$
0
0

Hello,

I've been trying to get the Powershell script "Move and Disable inactive computer accounts from Active Directory" working in my environment. http://gallery.technet.microsoft.com/scriptcenter/Move-and-disable-inactive-b1cf86c3

I have been unable to make this script work. I receive the below error. Any ideas? I have the Quest AD Management Shell 1.6.0 installed.


Get-QADComputer : Cannot bind parameter 'InactiveFor'. Cannot convert value "60-SizeLimit" to
type "System.Int32". Error: "Input string was not in a correct format."
At C:\Utilities\MoveInactiveComputers.ps1:30 char:30
+ Get-QADComputer -InactiveFor $NumOfDaysInactiveFor-SizeLimit 0-SearchRoot $searc ...
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-QADComputer], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Quest.ActiveRoles.ArsPowerShellSnapI
   n.Powershell.Cmdlets.GetComputerCmdlet

Registry or Command Line to set Local Security Audit Policy on local machine

$
0
0

How to set Local Security Audit Policy on local machine either by registry or command line.

Below settings are required to be set on multiple machines in workgroup environment.

Security Settings > Local Polices > Audit Policy

Audit account logon events
Audit account management
Audit directory service access
Audit logon events
Audit object access
Audit policy change


Pranay (MCSE, MCITP)


Using -match in an IF statement that is used in a foreach loop

$
0
0

Hello Everyone,

I have a script that is working, but I have a behavior that I cannot explain. This script asks will count the number of times a word is used inside a text file. The following script works.  However, if I change the order of the match statement I get an error. I have not been able to explain the difference even with a couple hours of research.  See the second code block for the changed version.  All I did was change ($w -match $wordsearch) to ($wordsearch -match $w). When I do this I get the the error

parsing "prepare) " - Too many )'s.
At C:\Users\Administrator\Desktop\story-count.ps1:8 char:4
+ if(($wordsearch) -match ($w)){

If anyone can help me understand this I would greatly appreciate it!

Thanks!

$filepath = read-host "Please type a file path"
$wordsearch = read-host "Please enter a word to search for"
$content = get-content $filepath -Delim ' '
$count = 0


foreach($w in $content){
if($w -match $wordsearch ){
    $count = $count + 1
    }   
}

Write-Host "The word $wordsearch was counted $count times."

Non-working code.

$filepath = read-host "Please type a file path"
$wordsearch = read-host "Please enter a word to search for"
$content = get-content $filepath -Delim ' '
$count = 0


foreach($w in $content){
if($wordsearch -match $w ){
    $count = $count + 1
    }   
}

Write-Host "The word $wordsearch was counted $count times."

How to Check files which is older than 14 days in particuler folder using IF condition in Batch script

$
0
0

Hi,

I have to check the zip files created before 14 days by using Batch script.

Any conditional statement needed ?

Thanks,

Jitu

class doesn't support automation 'getobject'

$
0
0

Hi all,

I have written a script to get a list of local users who are also part of local administrator group. But on some systems I'm getting an error as said in the subject. Below is the script I'm using. It works fins on some system but troubles on some. Please help.. Thanks..

strComputer = "."
SET objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
SET systems = objWMIService.ExecQuery("SELECT name FROM WIN32_ComputerSystem")
SET LocalUsers = objWMIService.ExecQuery("SELECT name FROM WIN32_UserAccount WHERE LocalAccount=True")
For Each system IN systems
	hostname = System.Name
Next
localgrpcomponent = chr(34) & "win32_group.domain='" & hostname & "',name='administrators'" & chr(34)
SET AdminUsers = objWMIService.ExecQuery("SELECT PartComponent FROM WIN32_GroupUser Where GroupComponent=" & localgrpcomponent)

SET WSshell = Wscript.CreateObject("Wscript.Shell")
SET objFSO = CreateObject("Scripting.FileSystemObject")
SET objFolder = objFSO.CreateFolder(WSshell.ExpandEnvironmentStrings("%SystemDrive%") & "\UserLog")
logfile = objFolder & "\" & hostname & ".txt"
SET objFile = objFSO.CreateTextFile(logfile, 2, True)
For Each ADMuser IN AdminUsers
		name = split(split(ADMuser.partcomponent, "=")(2), chr(34))
		domain = split(ADMuser.partcomponent, chr(34))(1)
		For Each User IN LocalUsers
			IF User.name=name(1) And Lcase(User.name) <> "administrator" AND domain = hostname Then
				objFile.WriteLine(Date & " " & Time & "|" & "User in Local Admin Group:"  & " " & domain & "\" & User.name)
			End IF
		Next
Next
objFile.Close


Regards, Darshan G. Parab

Convert PDF to Word

$
0
0

I have a PowerShell script that converts Word documents to PDF.  Now that Word 2013 can read PDF's directly and can then save the PDF as a Word document, is there a way to do so in PowerShell?

Thanks for the help.

need to list all PST on each PC's connected to Network

$
0
0

HI

We are in process to purchase a e-mail archiving solution. We are thinking for CAPACITY based licensing option. 

For that purpose I need to know details of each PST on each PC in our domain. 

Is there any way to gather the list containing all PST with size to a centraly located excel or ms access file ? 

I tried first  "d:\dir /s  *.pst > c:\pstlist.csv" its giving optput as 

"D:\>DIR /S  *.PST
 Volume in drive D has no label.
 Volume Serial Number is CAD8-80CF

 Directory of D:\oldData\My Documents

06/18/2002  02:08 PM            65,536 archive.pst
               1 File(s)         65,536 bytes

 Directory of D:\oldData\MyMAils\VNPandit

11/30/2010  09:08 AM       102,614,016 archive.pst
01/15/2014  08:49 AM        32,523,264 VNPandit.pst
               2 File(s)    135,137,280 bytes

 Directory of D:\oldData\users\aabodake\AppData\Local\Microsoft\Outlook

06/25/2012  05:08 PM           271,360 SharePoint Lists.pst
               1 File(s)        271,360 bytes

 Directory of D:\oldData\users\vnpandit\AppData\Local\Microsoft\Outlook

01/15/2014  08:49 AM     2,722,382,848 archive.pst
01/15/2014  08:49 AM           271,360 Personal Folders(1).pst
               2 File(s)  2,722,654,208 bytes

     Total Files Listed:
               6 File(s)  2,858,128,384 bytes
               0 Dir(s)  183,056,760,832 bytes free" 

it showing the line directory of which not useful for me I want to remove this line. 

I tried using "d:\dir /s /b *.pst > c:\pstlist.csv" but this command  is only giving me list and but I need to have size also.

Find OS Install date across all computers in AD

$
0
0

Hello,

I'm kind of a new guy at this. I have parts of the script, but I don't know how to link them together. I want to generate a list of computers with the date the OS was installed on. Here's what I got:

It's all a bit of a mess I know... but I would like to incorporate try/catch (see below)

get-adcomputer -filter * -SearchBase "OU=Desktop Machines,OU=Computers,OU=MyBusiness,DC=example,DC=example"
Get-WmiObject win32_operatingsystem -ComputerName
$wmi.converttodatetime($WMI.installdate)
$result = ForEach ($computers) { 
        Try {([WMI]'').ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).InstallDate) -erroraction stop}
        Catch {Write-Warning "Unable to connect to $c" }

Hope someone can help!

Kind regards,

Sam Colman

Powershell Script to obtain current members of groups inside group of Domains Admins

$
0
0

Hi,

I have some servers that inside group domains admins i have users and groups. I need to list this groups and his members like the example:

Server 1              Group 1                              User 1

Server 1              Group 1                              User 2 

Server 1              Group 1                              User 3

Server 2              Group 1                              User 1

Server 2              Group 1                              User 2 

Server 2              Group 1                              User 3

Server 2              Group 1                              User 3

After that i need to output the information in a vbs. The is some script tha can help me whith that?

Grateful


Powershell Script that adds dns suffix for this connection, append these dns suffixes (in order), Add WINS Server Entries

$
0
0

Hi,  

I'm currently trying to write a powershell script for both Sever 2008 R2 and Server 2012 that configures the TCP/IP V. 4 Network Interface settings.   I have figured out how to set the static IP address, subnet mask and default gateway settings using the netsh command.   I'm having issue figuring out how to configure the following settings

Add DNS Suffix for this connection to "abc.com"

Append these DNS Suffixes (In Order) abc.com, abcd.com, abcde.com

Uncheck Register this connection's address in DNS

Add WINS Server IP Address entires  

I just started using Powershell and am trying to learn on the fly.   Any suggestions or links for help would be greatly appreciated.  

Thanks,

Kevin C.

Report AD display name & computer hostname

$
0
0

Hi

Id like to keep track of which user is using which computers on our network and use the data gathered to feed into other scripts.

Ideally 3 columns,  Windows display name,    ad account name,  Computer hostname

This would be very useful. Can anyone get me started

Thanks for reading

Confuseis


confuseis

Power shell Copy-Item woes

$
0
0

Hi There,

I've a requirement where I need to copy certain directories and certain files from a patent directory such as 

file, dir, dir, dir\dir\dir\file, dir\file

This is what i tried to do. When the command didn't work, i also tried with Robocopy (in the code comment) but to no avail- 

$sourceDir="c:\application"$backupDir="c:\backup"$backupItems='file1','dir1','dir2','dir3\sub-dir\sub-dir\file', 'dir4\file'if(test-path $backupDir )<br/>{foreach ($itemin$backupItems)
{
copy-item $sourceDir\$item-destination $backupDir\$item-container -force -recurse<br/>#robocopy /E $sourceDir\$item $backupDir\$item <br/>
}
}

The issue that happens in the first case is, the nested paths are not created on the backup directory and hence error.

With RoboCopy, it treats the files as well as directories and fails to find the directory in source.

Another way that i tried was to create the directories first and then copy the files. This way, it is creates a nested directory for the dir1 and dir2.

Code for that - 

$sourceDir="c:\application"$backupDir="c:\backup"$backupItems='file1','dir1','dir2','dir3\sub-dir\sub-dir\file', 'dir4\file'$dirs='dir1','dir2','dir3\sub-dir\sub-dir','dir4'if(test-path $backupDir )
{for ($i=0;$i-le$dirs.length; $i++)
{$dir=$dirs[$i]
new-item $backupDir\$dir-force -itemtype directory
}foreach ($itemin$backupItems)
{
copy-item $sourceDir\$item-destination $backupDir\$item-container -force -recurse#robocopy /E $sourceDir\$item $backupDir\$item 

}
}

any insights will be helpful.

Powershell Upload Data without SQL

$
0
0

Hi,

I'm currently doing a script that is reporting on a server but we do not have SQL installed nor do we have the possibility of installing SQL at present, is it possible to store data in a text file or xml file and get powershell to compare the data.

For example the main purpose of this is every month it will report disk space and what i would like is it to check a file for previous data and show the growth.

Unfortunately every time i search for something it's always people giving examples of SQL so just wondering if anyone has some examples they can share.

Thanks

Alex

Technet script: 'List Membership In Privileged Groups'

$
0
0

Hi,

There's an excellent script for auditing members of privileged groups in Active Directory and as I've used this in numerous environments I think I've found a slight issue.

The below page suggests here is a good place to report bugs... :)

http://gallery.technet.microsoft.com/scriptcenter/List-Membership-In-bff89703

Original blog and my comment:

http://blogs.technet.com/b/askpfeplat/archive/2013/04/08/audit-membership-in-privileged-active-directory-groups-a-second-look.aspx#171707

In short the issue is in multi-domain forests the code running under Powershell v3 doesn't correctly query the privileged groups and the generated csv's aren't correct.

My post:

[quote]Hi Mark, I believe I've fixed your issue :) It seems when running in a multidomain forest and with Powershell v3 the findall() function fails. From memory the line: Foreach ($uniqueMember in $uniqueMembers) doesn't seem to select distinct single entities from the array $uniqueMembers so when calling getUserAccountAttribs it throws a fit as it's passed 10-100s of accounts.

What's interesting is this issue is resolved in Powershell v2 and only apparent in v3. Doug - I'd be interested to know if you figure this out - maybe incorporate the fix with the count fix you mentioned for the next version? Much appreciated, David[/quote]

Viewing all 15028 articles
Browse latest View live


Latest Images

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