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

the get-networkstatistics.ps1 script isn't working for me

$
0
0

Hello,

This post is regarding the get-networkstatistics.ps1 script.

I run the command once to implement the function (I have debug/trace level set to two with 'set-psdebug -trace 2'):

I then attempt to run the script against the local computer:


I then ran the same script against another machine.


Execution policy is set to unrestricted during the commands above:

Can someone tell me what the prerequisites are for this script to run successfully?


Export Permissions - Active Directory Sites And a Services

$
0
0

Hi all

I need to Export all Subnets to another Machine. I got it trough the comand Get-ADReplicationSubnet -Properties *.

The problem is that the permissions are not exported.

What can i do?

internetexplorer.application navigate error

$
0
0
Hi All
I have a simple vb script that opens IE window and navigates to a link:

Set oIE=createobject("internetexplorer.application")
Do While (oIE.Busy)
Wscript.Sleep 250
Loop
oIE.navigate "http://MyLink.htm"

Most of the time it works fine but sometimes I am getting "Invalid procedure call or argument" error on  oIE.navigate line
Is there anything I am doing wrong?

Thanks

Having problems with setting Applocker policies GPO through Powershell

$
0
0

I built a powershell script to automate the setting of a GPO for Applocker so it can be deployed on multiple domains. Unfortunately I receive a weird error when the GPO has been set, in the console of powershell everything seems to work but when I open the GPO itself in GPedit. I receive the following error: "HRESULT E_FAIL has been returned from a call to a COM component" and I need to remove the gpo manually and add it again manually which removes the point of the script. I also replaced all the GUID with new ones and that also didn't work.

Some piece of the itself:

New-GPO -Name "$GPOApplockerN"
New-GPLink -Name "$GPOApplockerN" -Target "$domainroot"| Out-Null
$guidgpo=Get-GPO -name "$GPOApplockerN" | select-object -expandproperty ID

sc.exe config appidsvc start= auto
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe" -ValueName EnforcementMode -Type DWord -value 0
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\appx" -ValueName EnforcementMode -Type DWord -value 0
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\msi" -ValueName EnforcementMode -Type DWord -value 0
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\scripts" -ValueName EnforcementMode -Type DWord -value 0
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Explorer" -ValueName AdminInfoURL -Type String -value $url

#Create Rules in applocker
#exe
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\13f89ee5-b386-4373-972a-e3a46c224ae3" -ValueName Value -Type String -value '<FilePublisherRule Id="13f89ee5-b386-4373-972a-e3a46c224ae3" Name="Allow all Microsoft signed" Description="" UserOrGroupSid="S-1-1-0" Action="Allow"><Conditions><FilePublisherCondition PublisherName="O=MICROSOFT CORPORATION, L=REDMOND, S=WASHINGTON, C=US" ProductName="*" BinaryName="*"><BinaryVersionRange LowSection="*" HighSection="*"/></FilePublisherCondition></Conditions></FilePublisherRule>'
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\921cc481-6e17-4653-8f75-050b80acca20" -ValueName Value -Type String -value '<FilePathRule Id="921cc481-6e17-4653-8f75-050b80acca20" Name="(Default Rule) All files located in the Program Files folder" Description="Allows members of the Everyone group to run applications that are located in the Program Files folder." UserOrGroupSid="S-1-1-0" Action="Allow"><Conditions><FilePathConditionPath="%PROGRAMFILES%\*"/></Conditions></FilePathRule>'
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\a61c8b2c-a319-4cd0-9690-d2177cad7b51" -ValueName Value -Type String -value '<FilePathRule Id="a61c8b2c-a319-4cd0-9690-d2177cad7b51" Name="(Default Rule) All files located in the Windows folder" Description="Allows members of the Everyone group to run applications that are located in the Windows folder." UserOrGroupSid="S-1-1-0" Action="Allow"><Conditions><FilePathCondition Path="%WINDIR%\*"/></Conditions></FilePathRule>'
Set-GPRegistryValue -Name "$GPOApplockerN" -key "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\fd686d83-a829-4351-8ff4-27c7de5755d2" -ValueName Value -Type String -value '<FilePathRule Id="fd686d83-a829-4351-8ff4-27c7de5755d2" Name="(Default Rule) All files" Description="Allows members of the domain Administrators group to run all applications." UserOrGroupSid="S-1-5-21domain-512" Action="Allow"><Conditions><FilePathCondition Path="*"/></Conditions></FilePathRule>

Why can't I get this to work? I tried everything mentioned above. I even ran the script line by line and couldn't find anything.

Powershell: create scheduled task which repeats every other month?

$
0
0

Hi,

I have a Powershell-script to deploy windows updates every other month on PatchTuesday.

However I don't find a way to schedule it (via Powershell every other month). Please advise how this can be done.
 

$TriggerSchedule = New-ScheduledTaskTrigger -At "$ScheduledDatePatchTuesday" .... every other month

J.


Jan Hoedt

Powershell threat

$
0
0
I used NPE recently which returned a powershell file as a threat.  the following is the file 

Registry Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\"ExecutionPolicy".

Does this look legit?  I have run MalwareByte and it has detected no issues.

Parsing nested JSON

$
0
0

Hello,

I am parsing the JSON response data (got from Invoke-RestMethod). I would like to put the output into a table, selecting only the necessary columns. However, one of the column that I want to have in the table is nested in JSON.

When I use: 

Format-Table -Property id, name, parent
I get:

     id name                                    parent
     -- ----                                    ------
   6584 Jack                            @{id=1560; name=Mary}
   1563 Mark                            @{id=805; name=John}

Could you please help me how to have just Mary and John in the parent column?

Regards

uninstalling software on remote computers

$
0
0

Hi all

I am having difficulties trying to uninstall software from targeted PCs. For my initial research, i was testing uninstalling a software on my machine via WMIC. WMIC works great on a standalone device however when i tried to uninstall a software on another machine remotely i get an error

i tried using the txt document method as well and same error

Any ideas how i can connect to a pc remotely with wmic? i tried connecting with test device's IP address as well but that didn't change anything

If wmic does not work, can you advise what i need to do in powershell to achieve this?

Thanks in advance


Powershell: change default datetime format in script?

$
0
0
Hi,

I have an html report in which I include dates.
Now these dates appear in month/day/year. I want to prevent to need to change every date to format dd/mm/yyyy.
Practical example in SCCM:(Get-CMDeployment -CollectionName $CollectionX).deploymenttime gives 11/15/2017 09:15:33
whereas it should be 15/11/...

Is there a way to set it in beginning of script so dates are in correct format?
Tried
Set-Culture -CultureInfo de-de but that does not work.

Please advise.
J.

Jan Hoedt

VBScript: Error: Move folder Permission Denied + code: 800A0046

$
0
0

Hi All,

i tried move a folder YYYYmm format using below VBScript, move to destination same folder directory, YYYY\yyyyMM. However, command prompt shown me Permission Denied, Error Code: 800A0046.

server Date time format: mm/DD/yyyy, i use VBscript to twist to format DD/MM/yyyy to match folder.

CDATE(currDay+ "/"  + currMonth + "/" + CurrYYYY)

'How to use:
' type "archiver D:\root source folder" in command line eg: D:\Test\archiver\archiver.vbs "D:\Test\archiver"

DIM strLogFile
Const ForAppending = 8
'Wscript.StdOut.WriteBlanklines 100
Set FSO = CreateObject("Scripting.FileSystemObject")

strLogFile=WScript.Arguments(0) &"\Log\ARCHIVER_Log_" & Year(Date) & Month(Date) & Day(Date) & ".txt"

'Log\ folder not exists then create new folder
IF NOT FSO.FolderExists(WScript.Arguments(0) &"\Log\") THEN
		FSO.CreateFolder WScript.Arguments(0) & "\Log\"
END IF

Set objLogFile = FSO.OpenTextFile(strLogFile, ForAppending, True)

objLogfile.WriteLine NOW & ">> ------------ ARCHIVER BEGIN ------------------"
objLogfile.WriteLine ""
objLogfile.WriteLine Now & ">> Root Folder: " & WScript.Arguments(0)
objLogfile.WriteLine ""
archiver(FSO.GetFolder(WScript.Arguments(0)))
objLogfile.WriteLine NOW & ">> ------------ ARCHIVER END ------------------"
objLogfile.WriteLine ""
objLogFile.Close 


Sub archiver(Folder)

	DIM year_
	DIM month_
	Dim dt
	dt=now
	
	'output format: yyyymmddHHnn
	currMonth=Cstr(month(dt)) 	'current Month
	currDay=Cstr(day(dt)) 		'current day
	CurrYYYY=Cstr(year(dt)) 	'current Year
	'wscript.echo currMonth
	'wscript.echo currDay
	'wscript.echo CurrYYYY	
	
	archiveMonth = -6
	'Set myLog = objFSO.OpenTextFile(destinationPath, For_Writing, True)
        For Each Subfolder in Folder.SubFolders		
		IF LEN(subfolder.Name) = 8 AND ISNUMERIC(subfolder.Name) THEN
			year_ = MID(subfolder.Name,1,4)
			month_ = MID(subfolder.Name,5,2)
			

			objLogfile.WriteLine "Process Checking MM-DD-YY Now......"
			'objLogfile.WriteLine FormatDateTime(CDATE("01/" + month + "/" + year),2)
			'IF IsDate(CDATE("01/" + month + "/" + year)) AND DateDiff("m", Date, "01/" + month + "/" + year) < archiveMonth  THEN
			IF IsDate(CDATE("01/" + month_ + "/" + year_)) AND DateDiff("m", CDATE(currDay+ "/"  + currMonth + "/" + CurrYYYY), "01/" + month_ + "/" + year_) <= archiveMonth  THEN
				objLogfile.WriteLine archiveMonth '-6
				objLogfile.WriteLine IsDate(CDATE("01/" + month_ + "/" + year_)) 'True
				objLogfile.WriteLine NOW & ">> Processing >> " + Subfolder.Name
				destinationPath = year_ 'WScript.Arguments(0) + " " + year
				'Year folder not exists then create new folder
				IF NOT FSO.FolderExists(destinationPath) THEN
					FSO.CreateFolder destinationPath
				END IF
				IF FSO.FolderExists(destinationPath) THEN
					destinationPath = destinationPath + "\" + year_ + month_
					IF FSO.FolderExists(destinationPath) THEN
						objLogfile.WriteLine NOW & ">> Moving folder " + Subfolder.Name + " to destination: " + destinationPath
						Subfolder.Move destinationPath + "\" + Subfolder.Name
					ELSE
						'Year + Month folder not exists then create new folder
						FSO.CreateFolder destinationPath
						IF FSO.FolderExists(destinationPath) THEN
							objLogfile.WriteLine NOW & ">> Moving folder " + Subfolder.Name + " to destination: " + destinationPath
							Subfolder.Move destinationPath + "\" + Subfolder.Name
						ELSE
							objLogfile.WriteLine NOW & ">> ** ERROR: Unable to create folder: " + destinationPath	
						END IF
					END IF
				ELSE
					objLogfile.WriteLine NOW & ">> ** ERROR: Unable to create folder: " + destinationPath
				END IF
				'Wscript.StdOut.WriteBlanklines 1
				'objLogfile.WriteLine ""

			END IF
		END IF
        Next
End Sub

Error Message

Script: D:\....\Archived\archiver.vbs

Line: 71

Char: 7

Error Code: Permission Denied

Code: 800A0046

Source Code: Microsoft VBScript runtime error




mysqldump in powershell

$
0
0

Hi,

Need to put this in powershell, help please?

mysqldump -u remote -pr3m0t3@hs hs_db > c:\backup\hs_backup \hs_db_%date:/=%_%time:~0,2%-%time:~3,2%-%time:~6,2%.sql

Need the SharePoint Online site list based on Created Date.

$
0
0

I have requirement where i need to get the list of the SharePoint Online site collection created in the previous month.

And also the Size of it.


Abdul Haseeb

Script not working as expected

$
0
0

Hello All,

I have created the script to run the below given cmd line, but when i run the script the cmd executed on local machine where i run the script not the other machines,

Please check the script and advise me to correct it.

Option Explicit

dim inputfile,outputfile,objfile,fileobjfile,objshell,objtextfile,objwritefile,strcmdline,strcomputer

inputfile = "c:\temp\inputfile.txt"
outputfile = "c:\temp\outputfile.txt"


set objfile = createobject("scripting.filesystemobject")
set fileobjfile = createobject("scripting.filesystemobject")
set objshell = wscript.createobject("wscript.shell")

set objtextfile = objfile.opentextfile("c:\temp\inputfile.txt",1)
set objwritefile =  objfile.createtextfile ("c:\temp\outputfile.txt",8)

Do until objtextfile.AtEndOfStream

strcomputer = objtextfile.Readline

set strcmdline =objshell.exec ("C:\Program Files\1E\NomadBranch\NomadBranch.exe -precache")

objwritefile.writeline (strcomputer)

loop




THANKS SURESH M

Can I export an Outlook OST to PST using a script?

$
0
0

Hi all.  I would like to export my local OST file to a PST using a script (VB or otherwise).  Is this possible? 

To be clear, I know how to manually export my local OST to a PST (using Outlook 2013).  But I would like to carry this out via a script, if possible.

The ultimate objective of this particular task is to automate the process of the OST-to-PST export, and have it carried out on a weekly schedule.

I'm not asking for anyone to provide me with any actual code.  I just want to know if this would be possible via some kind of Windows script, and if so, perhaps a nudge in the right direction :-)

I am running Win 10, x64.

Thanks in advance.

Query size of an open file

$
0
0

Hi all. I would like to know how I can query the size of a file that is actively being written to. I've opened the file using:

$fdFile = New-Object System.IO.StreamWriter(New-Object IO.FileStream($FilePath, $mode, $access, $sharing))

When writing to the file I'd like the check the size of the file in order to determine if I need to roll the log not. The file will be in an open state when I want to check this.

Any help would be greatly appreciated.


-- Tim.


Command line parameters used twice

$
0
0
 I have a batch file that runs an Excel workbook with parameters on the same line. Excel takes in the parameters and runs its calculations based on these parameters. However, after Excel has run, the command processor processes all the parameters again, and I get a bunch of errors that say "Sorry. we couldn't find .... Is if possible it was moved, renamed or deleted?". There are several parameters on the statement that runs Excel and they are in double-quotes. How do I prevent the command processor from re-processing these parameters as separate statements? 

How to replace ^ symbol using powershell

$
0
0

Hello ,

I am still not able to find a solution how to replace  ^ symbol in  text files.

Can anyone provide the script in Powershell Please?

Thanks,

MJ

need powershell script that create and rename local user in remote machine

$
0
0

Hello Expert,

I need powershell script that to create a local user and rename it as "Administrator" name in remote computers.

Thanks
Richa

Set default value for variables ERROR

$
0
0

Hello, below is the code and when I run it, I get an error which I don't know how to fix? Or understand why it is happening?

function do-something {
[CmdletBinding()]

param(
[Parameter(Mandatory=$true,ValueFromPipeLine=$true,Position=0)][String[]]$ServerName
)
[String]$Name = 'TestName'
[String]$Site = 'TestSite'
[String]$Path = "C:\Temp\$Site"


foreach ($Server in $ServerName) {

    Invoke-Command -ComputerName $Server -ScriptBlock {
            
            New-Item -ItemType directory -path $Path
        }

    }

}




But If I run the debugger to see what's happening then the variables do have preset values???

[DBG]: PS C:\>> $Name
TestName

[DBG]: PS C:\>> $Site
TestSite

[DBG]: PS C:\>> $Path
C:\Temp\TestSite

Can someone please help me with this issue and also explain why of it.

Two similar scripts - both works in PS but when run in Task Scheduler, only one succeed

$
0
0

I'm having an struggle with two scripts, the scripts makes a check on users AD values and runs perfect from Powershell as the user.

when i then add the scripts to Task Scheduler, the one script runs as intended and send a e-mail, the other script just opens a notepad with the csv file, but does not send the e-mail, it does not throw an exception on the send mail process, so i'm quite confused, as they both work in PS but only the one works on Task Scheduler.

The working script:

# Time / Date Info
$start = [datetime]::Now
$midnight = $start.Date.AddDays(1)
$timeToMidnight = New-TimeSpan -Start $start -end $midnight.Date
$midnight2 = $start.Date.AddDays(2)
$timeToMidnight2 = New-TimeSpan -Start $start -end $midnight2.Date

try{
    Import-Module ActiveDirectory -ErrorAction Stop
}
catch{
    Write-Warning "Unable to load Active Directory PowerShell Module"
}
$reportTo='it@DOMAINNAME.com'
$reportFrom='IT (DO NOT REPLY) <donotreply@DOMAINNAME.com>'
$smtpServer='192.168.1.123'
$textEncoding = [System.Text.Encoding]::UTF8

$worksfolder="C:\Scripts\UserLastLogonCheck"
if ( !(test-path "$worksfolder")) {
    Write-Verbose "Folder [$($worksfolder)] does not exist, creating"
    new-item $worksFolder -type directory -Force 
}

$ou1="OU=Users,OU=DMN,DC=DOMAINNAME,DC=com"
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $OU1 -Properties Name,SamAccountName,LastLogonDate | Where {($_.LastLogonDate -lt (Get-Date).AddDays(-60)) -and ($_.LastLogonDate -ne $NULL)} | Sort | Select Name,SamAccountName,LastLogonDate | export-csv C:\Scripts\UserLastLogonCheck\userslastlogondateolderthan60days.csv -nti -Encoding UTF8

 $date = Get-Date
 $logfile = "C:\Scripts\UserLastLogonCheck\userslastlogondateolderthan60days.csv"
if($reportTo)
    {
        $reportSubject = "Users with last logon older than 60 days"
        $reportBody ="<font face=""calibri"">
    Script run date: $date<p> Attached is list of AD users within domain: Millwardbrown.dk with last logon date older than 60 days from today.</font>"
        try{
            Send-Mailmessage -smtpServer $smtpServer -from $reportFrom -to $reportTo -subject $reportSubject -body $reportbody -bodyasHTML -priority High -Encoding $textEncoding -Attachments $logFile -ErrorAction Stop 
        }
        catch{
            $errorMessage = $_.Exception.Message
            Write-Output $errorMessage
        }
    }
$stop = [datetime]::Now
$runTime = New-TimeSpan $start $stop
Write-Output "Script Runtime: $runtime"
# End

The problematic script:

# Time / Date Info
$start = [datetime]::Now
$midnight = $start.Date.AddDays(1)
$timeToMidnight = New-TimeSpan -Start $start -end $midnight.Date
$midnight2 = $start.Date.AddDays(2)
$timeToMidnight2 = New-TimeSpan -Start $start -end $midnight2.Date

try{
    Import-Module ActiveDirectory -ErrorAction Stop
}
catch{
    Write-Warning "Unable to load Active Directory PowerShell Module"
}
$reportTo='it@DOMAINNAME.com'
$reportFrom='IT (DO NOT REPLY) <donotreply@DOMAINNAME.com>'
$smtpServer='192.168.1.123'
$textEncoding = [System.Text.Encoding]::UTF8

$worksfolder="C:\Scripts\UserLastPasswordChangeCheck"
if ( !(test-path "$worksfolder")) {
    Write-Verbose "Folder [$($worksfolder)] does not exist, creating"
    new-item $worksFolder -type directory -Force 
}

$ou1="OU=Users,OU=DMN,DC=DOMAINNAME,DC=com"
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $OU1 -Properties Name,SamAccountName,PasswordLastSet,PasswordNeverExpires | Where {($_.PasswordLastSet -lt (Get-Date).AddDays(-60)) -and ($_.PasswordLastSet -ne $NULL)} | Sort | Select Name,SamAccountName,PasswordLastSet,PasswordNeverExpires | export-csv C:\Scripts\UserLastPasswordChangeCheck\userlastpasswordchangeolderthan60days.csv -nti -Encoding UTF8

 $date = Get-Date
 $logfile = "C:\Scripts\UserLastPasswordChangeCheck\userlastpasswordchangeolderthan60days.csv"
if($reportTo)
    {
        $reportSubject = $reportSubject = "Users with last password change older than 60 days"
        $reportBody ="<font face=""calibri"">
    Script run date: $date<p> Attached is list of AD users within domain: Millwardbrown.dk with last password change older than 60 days from today.</font>"
        try{
            Send-Mailmessage -smtpServer $smtpServer -from $reportFrom -to $reportTo -subject $reportSubject -body $reportbody -bodyasHTML -priority High -Encoding $textEncoding -Attachments $logFile -ErrorAction Stop 
        }
        catch{
            $errorMessage = $_.Exception.Message
            Write-Output $errorMessage
        }
    }
$stop = [datetime]::Now
$runTime = New-TimeSpan $start $stop
Write-Output "Script Runtime: $runtime"
# End

Viewing all 15028 articles
Browse latest View live


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