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

Variable for last hour (not last 60 minutes)

$
0
0

First time post, thanks for being gentle.  I have a script to export Windows logs (sys, app, etc...).  I am trying to export only events from the previous hour, not the previous 60 minutes.  For example, if I run the script at 11:20:00, I want all events from 10:00:00 to 10:59:59, not 10:20:00 to 11:19:59.  For collecting logs from previous day, the following works the way I want (00:00:00 - 11:59:59 yesterday):

$StartTime = [DateTime]::Today.AddDays(-1)

I'm at wits end on an analog for this with Hours.  As info, OS is 2012R2, PSVersion is 4.0.  More info upon request.


MySQL Database backup on windows server — not working with dynamic date

$
0
0

I'm able to schedule a windows task to create a MySQL database backup based on advice given in this stackoverflow question:

MySQL Database backup automatically on a windows server

This is my command:

mysqldump.exe --user=[user] --password=[password]  --host=localhost --port=3306 --result-file="c:\data\backup.sql" --default-character-set=utf8 --single-transaction=TRUE --databases "[database1]"

However, when I change my filename to include a dynamic date value as follows it doesn't create a backup anymore:

mysqldump.exe --user=[user] --password=[password]  --host=localhost --port=3306 --result-file="c:\data\backup%date:~10,4%%date:~7,2%%date:~4,2%.sql" --default-character-set=utf8 --single-transaction=TRUE --databases "[database1]"

Note: when I run this command via commandline it successfully creates a backup with the correct filename: backup.20160707.sql.

But for some reason when I run the Windows Task which runs this command it is not creating the backup file. When I look at history it appears to have finished successfully. What's going on?

This is the exact error:

Task Scheduler successfully completed task "\Backup srcinternet" , instance "{}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 2147942401.

PowerShell : Adding new column to DataSet

$
0
0

Hi All,

 I am working on one powershell script, I need to export sql results to csv,

but before that I need to add one column (not a static) with variable value to dataset or sql result and then export to csv.

e.g.

@var1 = $value

sql result  

col1	col1	col3	col4
2	xyz	xyz	test
2	abc	abc	test

I need to merge @var1 (dynamic value) to sql result

output should be in csv

var1	col1	col1	col3	col4
12	2	xyz	xyz	test
34	2	abc	abc	test

Please help me to resolve it.

Thanks


Powershell Script: Alert via Email if AD Group Membership Exceeded

$
0
0

Script Code & Author: http://apppackagetips.blogspot.com/2016/01/powershell-script-alert-via-email-if-ad.html

Recently discovered a Powershell script that would alleviate a few maintenance tasks concerning Licensing Management for products using Active Directory Security Groups. Very straight forward concept; define a maximum user limit and if exceeded, notify via e-mail. Unfortunately, I'm receiving an error I have been unable to overcome.

Error:

Cannot find an object with identity: 'CN=xxx,OU=XXX,OU=Departments,OU=Users,OU=XXX,DC=XXXX,DC=XXXX' under: 'DC=XXXX,DC=XXXX'.

Suspected Breakpoint:

$members=Get-ADGroupMember$_.Key

The above command line reproduces the error and no matter how I rework it to include a -Searchbase or -Identity parameters, I receive errors. Mind taking a look?

I have a scenario, that i want to write power shell script

$
0
0

Hi,

i'm trying to write script using function,arguments to split the string for machines and services like below. 

              

my requirement is to split the string with (#),(:),(,) 

•machine_name would be fully qualified name of the server
•s1,s2 are the service names
                DEV_Stop_Services_Before_Deploy
                                machine_name:s1,s2#machine_name:s1,s2#machine_name:s1,s2
                DEV_Uninstall_Services_Before_Deploy
                                machine_name:s1,s2#machine_name:s1,s2#machine_name:s1,s2
                DEV_Start_Services_After_Deploy
                                machine_name:s1,s2#machine_name:s1,s2#machine_name:s1,s2
                DEV_Install_Services_After_Deploy
                                machine_name:s1,s2#machine_name:s1,s2#machine_name:s1,s2

i wrote script as below. but i wouldn't find output as i need. please help me out.

Function ServicesinMacines([sting]$machineNames, [string]$serviceNames)

$MachinesInfo = $machineNames.Split("#");
foreach($EachMachineInfo in $MachinesInfo) {
write-host "\r" $EachMachineInfo;

$serviceNameinmachineName = $machineNames.split(:);
$machine = $machinetype[0];
$AllserviceNames = $serviceNames[1].split(",");
foreach($EachserviceName in $AllserviceNames) {

write-host "\r" $EachserviceInfo;

get-service -computername $machinenames -name $Servicesnames | % {

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

Thanks,

Prathap

New-Object System.Diagnostics.ProcessStartInfo "PowerShell" always kicks-off SYSWOW64 version

$
0
0

Hi,

I hope someone can tell me how to bypass this problem.

Background

I'm writing a script for starting/stopping an application pool in IIS. To do that I use the WebAdministration module. Since starting/stopping an application pool requires admin privileges I included code lines that self-elevates the script by using System.Diagnostics.ProcessStartInfo like this.

$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=New-Object System.Security.Principal.WindowsPrincipal($myWindowsID)

$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

if (-not ($myWindowsPrincipal.IsInRole($adminRole))) {
	# We are not running "as Administrator" - so relaunch as administrator

	$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
	$newProcess.LoadUserProfile = $false;

	$newArgs = [string]($PSBoundParameters.GetEnumerator() | ForEach-Object { '-{0} ''{1}''' -f $_.Key,$_.Value});
	$newProcess.Arguments = "-ExecutionPolicy ByPass -File " + $myInvocation.MyCommand.Definition + " $newArgs";
	$newProcess.Verb = "runas";

	[System.Diagnostics.Process]::Start($newProcess);

Problem

I run the script in the 64-bit version of PowerShell. But when the script kicks off the new process it starts the SYSWOW64 version of PowerShell resulting in all WebAdministration methods failing since they are 64-bit only.

Making this minor change doesn't solve it. Still kicks off the SYSWOW64 version of PowerShell.

	$newProcess = New-Object System.Diagnostics.ProcessStartInfo;
	$newProcess.FileName = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
	$newProcess.LoadUserProfile = $false;
How can I change the behaviour so the script can self-elevate and still use the 64-bit version of PowerShell?

gMSA + Task Scheduler v.4

$
0
0

Long time Windows administrator but recently just got into powershell. We run our scheduled task using gMSA accounts in our environment because it meets STIG's. In doing so, I learned how to create Scheduled Task using powershell since it is the only way to use gMSA with task. I searched these forums and found one post about modifying the xml but I don't quite understand the how to. I use the same ps1 script to create all my task and just edit the variables as needed. This is also good in case I have to rebuild a server or I get hit by a bus and the new admin understands how to do my job. But the task which need to run on a specified monthly date is eluding me.

Here is my go to script for creating task schedules for creating gMSA task. I cannot seem to figure out how to get it to run on a monthly basis. For example, I have one task I would like to run on the 25th of every month.

        #Path to powershell script
        $F = "c:\SchTsk\File_Management.ps1"

        #The first command uses the New-ScheduledTaskAction cmdlet to assign the action variable $A to the executable file tskmgr.exe
        $A = New-ScheduledTaskAction -Execute "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe" -Argument "-noexit -ExecutionPolicy Bypass -File $F"

        #The second command uses the New-ScheduledTaskTrigger cmdlet to assign the trigger variable $T to the value AtLogon
        $T = New-ScheduledTaskTrigger -weekly -DaysOfWeek Saturday -At 7am

        #The third command uses the New-ScheduledTaskSettingsSet cmdlet to assign the settings variable $S to a task settings object
        $S = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit 1:00:00 -MultipleInstances 2

        #The fourth command assigns the principal variable to the New-ScheduledTaskPrincipal of the scheduled task, domainname\gMSA_account$
        $P = New-ScheduledTaskPrincipal -UserId domainname\gMSA_account$ -LogonType Password -RunLevel Highest

        #The fifth command sets the description varible to $D for the task definition
        $D = "Edit C:\SchTsk\File_Management.ps1"

        #Register the scheduled task
        Register-ScheduledTask Monthly_File_Management -Action $A -Trigger $T -Settings $S -Principal $P -Description $D
Thank's

Check the validity of the directories and files names

$
0
0

Hi

I have this script

@echo off
setlocal enableExtensions disableDelayedExpansion

call :setValidPath "Windows_Files_Path" "%~1" "Enter the directory in which put the content of the ""Windows Setup Media"" volume image:"
call :setValidPath "iso_Path"           "%~2" "Enter the directory in which put the iso image file created:"
call :setValidPath "esd_File_Path"      "%~3" "Enter the directory in which put the esd unencrypted file:"
call :setValidFile "esd_File"           "%~4" "Enter the file to be converted which should be put in the %esd_File_Path% directory:"

echo(
echo Result:
echo Windows_Files_Path: "%Windows_Files_Path%"
echo iso_Path          : "%iso_Path%"
echo esd_File_Path     : "%esd_File_Path%"
echo esd_File          : "%esd_File%"

:: put your code here

endlocal
goto :eof


:setValidPath
:: %~1 variable to set
:: %~2 default value
:: %~3 text if default value is invalid
 setlocal
 set "input=%~2"
 set "text=%~3"
 set "first=1"

:validatePath
 set "invalid="
 :: validating
 :: example code for invalidating input if the given path does not exist
 if not exist "%input%" set "invalid=The Path you specified for %~1 ^("%input%"^) does not exist."

 :: insert code for additional validity checking

 if not defined invalid endlocal & set "%~1=%input%" & echo Valid: %~1=%input%& goto :eof
 echo(Invalid: %invalid%
 set /P ^"input=%text:""="% "
 goto :validatePath


:setValidFile
:: %~1 variable to set
:: %~2 default value
:: %~3 text if default value is invalid
 setlocal
 set "input=%~2"
 set "text=%~3"
 set "first=1"

:validateFile
 set "invalid="
 :: validating
 :: example code for invalidating input if the given filename is empty string
 if "" == "%input%" set "invalid=The Filename you specified for %~1 is the empty string."

 :: insert code for additional validity checking

 if not defined invalid endlocal & set "%~1=%input%" & echo Valid: %~1=%input%& goto :eof
 echo(Invalid: %invalid%
 set /P ^"input=%text:""="% "
 goto :validateFile

that should check the validity of directory names (with absolute path) and file in Windows 7 and above and save these elements in the respective variables.

I noticed that if I insert some valid directories or files but non-existent, the values of these elements are not saved in these variables. Why?

The validity of these values is used to make sure that the creation of these elements have always success using the above variables with the md and oscdimg commands.

So, how can I modify this script?

Thanks

Bye


Balubeto



BrowseforFolder using VBS in Windows 10

$
0
0

I have the following script that is used to open the file browser window so that I could select a file and then write the selected file name out to a text file.  It worked fine in Window 7 and 8.1 but not in Windows 10.

Dim objShell
Dim strFileName
Dim strFilePath
Dim objFile
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
Set objFile = objShell.BrowseForFolder(0, "Choose a file:", &H4000,17)
strFileName = objFile.Title
strFilePath = objFile.self.Path
Set ts = objFSO.CreateTextFile("C:\Temp\Folder.txt",True)
ts.Write strFilePath
ts.Close

It opens the window to select the folder and file but when I click OK  I get the following error:

script: c:\Users\xxxxx\desktop\filelist.vbs

Line: 8

Char: 1

Error: Unspecified error

Code: 80004005

Source: (null)

If I set the &H4000 to &H0001 which means to only show folders I can select a folder and it works fine.

From other research I've seen it looks like this has to do with the version of the shell32.dll.

Anyone know of another way to allow a user to select a file and getting back the selected file's path and name?

Thank you!

Need a better way to filter

$
0
0

I have started a powershell script (my first one) with some help from other posting examples. It may be crude but so far its doing what I need but I am stuck on the best way to accomplish my filter with the Where-Object.

Background

With Get-ChildItem I am getting a list of folders in a file share that are 3 levels down. I now need to filter out using the following criteria but I am struggling to get it right or know if its even possible. From the example folders (folder name [INT######-YY]) below I want to filter all folders that are not (CurrentYr OR PriorYr OR NextYr). So far  believe I have this figured out as well.

But here is where it gets complicated, I am also hoping if the folder has been created in the last 1 yearbut follows the naming convention where the folder name ends with "-YY" it will be excluded (-notmatch) from the filter. If staff make up their own folder names it will be included in the Where-Object filter. All matching folders will be be moved (archived) to a new location.

Eg Current date is Jul 8, 2016, all folders flagged with a '*' should be in the filter and eventually moved.

Folder PathCreate Date
K:\B\Bills Towing\ABC123456-13Jul 10, 2013  *
K:\B\Bills Towing\ABC123456-14Jul 10, 2015
K:\B\Bills Towing\ABC123456-15Jul 10, 2015
K:\B\Bills Towing\ABC123456-16Jul 10, 2016
K:\B\Bills Towing\ABC123456-CDA-15Sep 10, 2015
K:\B\Bills Towing\ABC123456-TS-13Mar 12, 2013  *
K:\B\Bills Towing\ABC123456-TS-16Mar 08, 2016
K:\B\Bills Towing\ABC123456-16 MiscTextMar 08, 2016  *
K:\B\Bills Towing\MiscFolderNameMar 08, 2016  *

Below is one of the variations I have been trying to use with (), or without but I could use some direction, thanks.

Note: For now I am manually entering the "-YY" in the script but I have been testing the Get-Date and will use variables once I get the rest of the script working.

$MoveList = $ThirdLevel |
        Where-Object { ($_.FullName -notmatch "-15$" -and $_.FullName -notmatch "-16$" -and $_.FullName -notmatch "-17$") `
        -and $_.CreationTime -lt (Get-Date).AddDays(-365)}




Stunpals - Disclaimer: This posting is provided "AS IS" with no warranties.

How to uninstall an instance of Microsoft SQL Server 2008 R2

$
0
0
I basically want to uninstall (remove) an instance in SQL Server 2008 R2.  I surfed the net and was not able to find anything that works.  Can someone show me how to do it using PowerShell Script?

VBScript

$
0
0

Hello everybody,

I have a problem: 

I am working on this project: https://github.com/tim241/Duckyscript2VBScript

I need to send the windows key with multiple other keys. But VBScript does not support that. Can Microsoft not make an Update? Because it is not updated in like 20 years now and I really need it for my project I worked hard on it so if there won't be any update then I worked for nothing(I have autism and am 14)

anyway 

kindly Regards,

Tim

Somebody Help on ADAM Vbscripts

$
0
0

I am unbale to find the sample scripts for Active directory application module (ADAM), MS says it should be on  \LABS_DEMO\LABS\VBScript directory , I  have the downloaded and installed the ADAM from (https://www.microsoft.com/en-in/download/details.aspx?id=4201), but cant find any such directory, please someone help me.

or share the sample Lab scripts.

VB.NET - Update AD attributes -Need Help

$
0
0
I am getting "Server is Unwilling to process the request."
I need to update the Email ID field for users in AD using VB.net, I am able to search the users in AD all okay, not able to update any field, however.

Even tried to update other fields "homePhone", that too fails with same error, please help.

'' Hers my code..

Dim ADEntry As New DirectoryServices.DirectoryEntry("<Domain Name>")

Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry) Dim Result As String ADSearch.Filter = ("(samAccountName=" & UserName & ")") ADSearch.SearchScope = SearchScope.Subtree Dim MachineFoundAD As SearchResult = ADSearch.FindOne() If Not IsNothing(MachineFoundAD) Then Dim mailID As String Dim attrUpdate As New System.DirectoryServices.DirectoryEntry(MachineFoundAD.Path) Result = MachineFoundAD.GetDirectoryEntry().Properties.Item("cn").Value MsgBox("FOUND USER " & Result) ' Getting Search Results fine attrUpdate.Properties("mail").Value = "somethng@test.com" attrUpdate.CommitChanges() End If End Sub


I am getting "Server is Unwilling to process the request."
I need to update the Email ID field for users in AD using VB.net, I am able to search the users in AD all okay, not able to update any field, however.

Even tried to update other fields "homePhone", that too fails with same error, please help.



Change user home folder permission

$
0
0

Hi,

My user's home folder is located on Windows server 2012. Originally domain administrators and user themselves have full permission on the user's folder, but don't know what happened, all user home folder's permission are changed. Maybe someone accidentally changed the permission on top parent folder and replaced for all sub-folders. We have hundreds of home folders. Is there a way I  can replace the permission for each home folder with full permission for Administrators and the owner of the folder instead of going to each folder which would be very time consuming.   

Many thanks,


Grace


Need help with a monitor then move and rename script

$
0
0

I am writing a script that will monitor a specific directory for any newly created sub-directory created by a testing program when a students grade is posted.  Then check the contents of the newly created sub-directory and look if any .csv file exists.  If it does move and rename(append date and time) the file to a different directory secured by permissions so the students will not have access to it.

I am stuck on how to identify and  search the newly created sub folder for any .csv file?????

This is what I have so far ( I didn't use word wrap in notepad++ so pardon the lack of line breaks)

'set directory path E:\test to monitor

strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
SqlQuery ="SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE Targetinstance ISA 'WIN32_SubDirectory' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""E:\\\\test""'"
Set colMonitoredEvents = objWMIService.ExecNotificationQuery (SqlQuery)

'get result of newly created subdirectory and check for the existence of a .csv file
Do
Set objLatestEvent = colMonitoredEvents.NextEvent
Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists("?????????\*.csv") Then
    Set objFolder = objFSO.moveFile("????????????\*.csv")
Else
    Wscript.Echo "File does not exist."
End If

'the below echo will output the path to the new target directory for search but how can I use this info in the script?
Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop

Thanks in advance

v/r

D

Active Directory Web Services and Get-ADGroupMember

$
0
0

I have an issue when using Get-ADGroupMember on Server 2008 R2 SP1 Domain Controllers. There is a 5000 member limit on Group Membership as explained in the following link https://technet.microsoft.com/en-us/library/dd391908(WS.10).aspx.

The message is as expected "Get-ADGroupMember : The size limit for this request was exceeded".

When I add the line to the Microsoft.ActiveDirectory.WebServices.exe.config file  <add key="MaxGroupOrMemberEntries" value="7000" /> the error continues, however the message changes to "Get-ADGroupMember : Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running".

I have also added the "OperationTimeout" value which makes no difference. I have set this to five minutes as per the following entry <add key="OperationTimeout" value="00:05:00" />

I know that we could rewrite the PowerShell scripts to not use Get-ADGroupMember, however the preference would be to keep the scripts as they are.

The environment is a large environment and it would be our preference to have Get-ADGroupMember working.

The DC's are running .NET 4.5, cureent domain functional level is Windows Server 2008 R2

I am after any help on making this work?

Thanks in advance.


David Furlong


getting an error

$
0
0

i am using the script for bulk users creation in my ad as described in this blog "https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Bulk-Create-0927c0c0", but i am getting the below error can somebody help me pls ...

error msg:

New-ADUser : Directory object not found

At C:\AD Bulk User Creation\bulk_ad_user_create.ps1:28 char:4

+    New-ADUser @NewUserParams

+    ~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (CN=Sahil Koul,O...ctcorp,DC=local:String) [New-ADUser], ADIdentityNotFo

   undException

    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M

   icrosoft.ActiveDirectory.Management.Commands.NewADUser

New-ADUser : Directory object not found

At C:\AD Bulk User Creation\bulk_ad_user_create.ps1:28 char:4

+    New-ADUser @NewUserParams

+    ~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (CN=Ravinandana ...ctcorp,DC=local:String) [New-ADUser], ADIdentityNotFo

   undException

    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M

   icrosoft.ActiveDirectory.Management.Commands.NewADUser

New-ADUser : Directory object not found

At C:\AD Bulk User Creation\bulk_ad_user_create.ps1:28 char:4

+    New-ADUser @NewUserParams

+    ~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (CN=Rohith K E,O...ctcorp,DC=local:String) [New-ADUser], ADIdentityNotFo

   undException

    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M

   icrosoft.ActiveDirectory.Management.Commands.NewADUser


Run Powershell Chkdsk script on multiple servers

$
0
0
I wrote a powershell chkdsk script which runs chkdsk on multiple servers and for all the drives in it and return the values. I've diverted the output to a notepad. The issue is when I run the script it is throwing Unknown error code '3' for few servers and in few servers it fails to run. What can cause this problem?

run dos command on file in all subfolder of "test"

$
0
0

I have written a script to capture all files within the folder, but how do I run a program with dos command for only files in the folder and it subfolder?

$files = get-childitem c:\test -recurse

foreach($file in $files){

$filesCounts = $files.Count

if(!$filesCounts)

{

$filesCount = 1

}

$intNumberfiles++

& "C:\program files (x86)\program\program.exe" -password KIVnow C:\test\.\$file

}

Viewing all 15028 articles
Browse latest View live


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