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

Am i able to use Powershell to chose (or restrict) sleep power states (S-states) in Windows 10?

$
0
0
Hi,

When my PC enter a sleep mode it stucks. I checked the powercfg command.

powercfg /AVAILABLESLEEPSTATES command provide this output: 

 

The PC does not have any mention of S-state in BIOS.

I want to state explicitly that i want PC to enter S3 state, and i want torestrict system to S3 state only (that is - to explicitly prevent system from entering S0, S1, S2 states). How do i do this? Does Windows 10 have any means to deal with ACPI whether directly or indirectly?

I want to say to system: when i press a sleep button - enter S3 and do not enter S0 or S1 or S2.

How do i choose or restrict S-states in Windows 10? (In order to prevent computer from entering wrong sleep state and choose the right one.)

Thanks.

How to link exe to the icon available in system tray

$
0
0

Problem:- i am able to add the icon in the system tray but when i click (left click ) nothing happen, so basically i want to add or link the application exe which i have developed with the icon i have added in the system tray.

i am able to create the short cut using the below line of code 

New-Item -ItemType SymbolicLink -Path "path" -Name "abc" -Value "path\abc.exe"

and using below code to add the icon in the system tray.

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$icon =[System.Drawing.Icon]::ExtractAssociatedIcon('path\abc.exe') 
$sys = New-Object System.Windows.Forms.NotifyIcon
$sys.Text = "ABC"
$sys.Icon = $icon
$sys.Visible = $true

and also tried with creating registry entry but no luck.

Set-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer EnableAutoTray 0

hope i am able to explain my problem.


Prashant Dev Pandey LIVE IN YOUR OWN WAY Please remember to mark the replies as answers if they help

Powershell regex working but -match regex doesnt work?!

$
0
0
Hello everyone,
I have the following Code:

$String ="/line/anotherline
/line2/dasda 22 3g 7% /home
line3 33 5g 10% /home2"

$String.GetType() # = System.Object
$String = $String -split "`r`n"
$String.GetType() # = System.Array

for($i = 0 ; $i -lt $String.Count ; $i++)
{
     if($String[$i] -match "^[\/\w+|w+]\w+.*\%.*\w+$)
     {
          $Array += $String[$i] + "`n"
     }
     else
     {
          $a += $String[$i] + "`n"
     }
}

The regex working on regex101 but when i run it even like this:
$String[0] -match "^[\/\w+|w+]\w+.*\%.*\w+$ # = False
$String[1] -match "^[\/\w+|w+]\w+.*\%.*\w+$ # = False
$String[2] -match "^[\/\w+|w+]\w+.*\%.*\w+$ # = False
I get fail every single time!

however when i do the following:
$New_Array = @("/line/anotherline","/line2/dasda 22 3g 7% /home","line3 33 5g 10% /home2")
and i test the following:
$New_Array [0] -match "^[\/\w+|w+]\w+.*\%.*\w+$ # = False
$New_Array [1] -match "^[\/\w+|w+]\w+.*\%.*\w+$ # = True
$New_Array [2] -match "^[\/\w+|w+]\w+.*\%.*\w+$ # = True

Why this is happening?
I'm clueless...

Thanks in advanced,
Tal.

Event based 'Event Log monitoring' PowerShell script

$
0
0

I'm struggling to create an event based PowerShell script to continiously monitor certain events that are happening on a computer. 

First of all, I tried to base my script on a snippet I found online (see the code under this text).

I noticed the use of '[System.Diagnostics.EventLog]' which is OK if you use 'old' logs like 'System', 'Application'..,
but this doesn't work for 'new' log files like 'Microsoft-Windows-Wired-AutoConfig/Operational' where I'm looking for ID's 15500 and 15501
(Using 'Get-EventLog' doesn't show this log, but 'Get-WinEvent' does)

So I've been trying different things but I can't figure out how to get this working for the 'new' logfiles.

Anyone has any idea?

# set the event log name you want to subscribe to
# (use Get-EventLog -AsString for a list of available event log names)
$Name = 'Application'

# get an instance
$Log = [System.Diagnostics.EventLog]$Name

# determine what to do when an event occurs
$Action = {
    # get the original event entry that triggered the event
    $entry = $event.SourceEventArgs.Entry

    # do something based on the event
    if ($entry.EventId -eq 1 -and $entry.Source -eq 'WinLogon') 
    {
        Write-Host "Test event was received!"
    }

}

# subscribe to its "EntryWritten" event
$job = Register-ObjectEvent -InputObject $log -EventName EntryWritten -SourceIdentifier 'NewEventHandler' -Action $Action


# use a loop to keep PowerShell busy. You can abort via CTRL+C

Write-Host "Listening to events" -NoNewline

try
{
    do
    {
        Wait-Event -SourceIdentifier NewEventHandler -Timeout 1
        Write-Host "." -NoNewline

    } while ($true)
}
finally
{
    # this executes when CTRL+C is pressed
    Unregister-Event -SourceIdentifier NewEventHandler
    Remove-Job -Name NewEventHandler
    Write-Host ""
    Write-Host "Event handler stopped."
}

Folder Template Batch File

$
0
0

Dear Scripting guys,

My name is Mark and i'm an engineer. We use Solid Edge for our base CAD modelling and are currently in testing phase to implement SEDM. SEDM is a basic PLM Software package included with Solid Edge.

Windows explorer is used to view the SEDM vault folder.  For the first setup of this folder, I selected all the columns in the folder view i required. I applied this folder style to all sub folders through folder properties dialog and folder options dialog. I turned off my pc and now i need to reset the view. The complete template I have set up is missing. If this problem occurs for each colleague, I have to reset the folder templates for each colleague on monday and tell them not to turn off their pc. But then this task will become a standard task for me to do first thing in the morning each monday (we are working with 15 Solid Edge users). So i was thinking of a sort of batch file to setup the folder template on it's own. Then each colleague just run's the batch file, or I put the batch file in the startup folder of windows. So this so called batch file should be doing the following:

-go to the folder of the SEDM Vault

-Right click on a column > more

-Turn on the view for specific columns for example: Title, SE Status, Author, Name (and if possible with a fixed column width for each)

-Apply this to each sub folder

 

Still haven't found a good solution for my problem. Any help is welcome and if someone has found any work arround i'm glad to hear this.

 

Thanks in advance,

 

Markona12


Active Directory Organization unit Copy/Backup/Restore ACL

$
0
0

This script does copy ACL security, it works perfect.

But I want also backup of the old security on the OU where I'm replacing the ACL with the copy data.

For the backup I used the Export-Clixml method and import it again.

But I noticed when importing it again the TypeName changes to: Deserialized.System.DirectoryServices.ActiveDirectorySecurity

My question is how can I Re-Serialize this again? I did figure out it won't let me restore the ACL as long it's Deserialized.

#
# Description: Copy OU ACL
#

# Load Modules
Import-Module activedirectory

# Set Variables
$SourceOU = "OU=Users,OU=TestOU,OU=Testing,DC=test,DC=com"
$DestinationOU = "OU=Users,OU=ExampleOU,OU=Testing,DC=test,DC=com"
$ACLBackupFile = 'C:\WORK\2019 - 07\ACL_Backup_test.clixml'

### Start Script ###
Set-Location AD:\

# Backup Destination ACL for restore purpose
$ACL_Backup = Get-ACL -Path $DestinationOU
Export-Clixml -InputObject $ACL_Backup -Path $ACLBackupFile -Verbose

# Get ACL Data from Source
$ACL = Get-ACL -Path $SourceOU

# Disable Inheritance
$ACL.SetAccessRuleProtection($true,$true) 

# Set security
set-acl -aclobject $ACL $DestinationOU -Verbose

### Stop Script ###

### Backup RESTORE ###
$RestoredACL = Import-Clixml -Path $ACLBackupFile
[System.DirectoryServices.ActiveDirectoryAccessRule]::serialize($RestoredACL)
set-acl -AclObject $RestoredACL $DestinationOU -Verbose -WhatIf

### END Restore ###


Remote Bitlocker Script Issue

$
0
0

Having an issue with my script: "group policy settings require that a recovery password be specified..."

It shows key protectors added, but not saving to AD

Here is my script:

$List = Get-Content ".\list.txt"  
Start-Transcript -Path ".\bitlockertranscript.txt" -Force 
foreach ($Computer in $List) {  
  
        if (test-Connection -ComputerName $Computer -Count 1 -Quiet ) {   
          
            Get-ADComputer -Identity $Computer -Property * | Select Name,OperatingSystem
            Get-WmiObject -class Win32_Tpm -namespace root\CIMV2\Security\MicrosoftTpm  -computername $Computer | fl IsActivated_InitialValue, IsEnabled_InitialValue, IsOwned_InitialValue  
            $BitLocker = Get-WmiObject -ComputerName $Computer -Namespace Root\cimv2\Security\MicrosoftVolumeEncryption -Class Win32_EncryptableVolume
            $id = $BitLocker.GetKeyProtectors(3).volumekeyprotectorid | Select -First 1

    manage-bde.exe -cn $Computer -protectors -adbackup c: -id $id
            manage-bde.exe -on C: -cn $Computer
          
                    } else  
                      
                    {"No Connection to $Computer"  
              
                    }      
          
}
Stop-Transcript 

Creating an AD dynamic group, based on OU membership - refreshing group based on OU

$
0
0

Creating an AD dynamic group, based on OU membership - refreshing group based on OU

The goals here:

1) Create a single script (PS, VBS, whatever)

2) Remove all members from a group

3) Listing all current users inside an OU and put all thoses users inside the "emptied" group on 2)

It´s possible?

I found some scattered scripts, but some VBs, some PS, sometimes using DS*.exe, but it´s hard to find a single entity doing all this, but maybe combining two separated scripts (2 and 3) could do the trick

Any ideas?


IPv6 DNS configuration

$
0
0

Hi,

i want configure my IPV6 DNS entries with a script.

The script is generally working. The only probolem i am having is, that the command is not accepting a variable and i do not knwo why.

If I add the content of the variable manually then its working.

Working:

set-DnsClientServerAddress -InterfaceIndex 4 -ServerAddresses ("2a01:a080:1e0:1920:26aa:8871:ddc0:cc9e","2a01:a080:1e0:1920:5aa1:d260:ba56:3240")

Not working:

set-DnsClientServerAddress -InterfaceIndex 4 -ServerAddresses ($variable)

The type of the varaibale is STRING.

You can see the error in the picture.

Import a HTML bookmarks export from Firefox into Edge browser

$
0
0

Hi Guys,

We're rolling out Edge and need to automate the import of favorites from Firefox, into Edge. Firefox can automatically backup it's favs to a .html file , which is fine, but importing these in a zero-touch way for users is another beast entirely.

I'm a novice at powershell (learning everyday...) and have considered the following options, but could really use some guidance or ideas:

1. Use something like AutoIT module for powershell to automate the UI and use the inbuild Edge favs import (via browser settings) to do the job.

2. Using powershell to parse the .html document containing the favorites data, strip out the <a> tags for URLs and <h3> tags for folders and create 'internet shortcut' files (in the style that IE stores Favs) and then use a second script (which is available on Technet) to auto-import from IE to Edge.

3. some third party browser syncing plugin that we can configure to run-once on the machines when we issue them to staff.

4. I can't see any GPO's or 'first-run' style settings that can import the favorites.

Any ideas? I can't see any noise online about doing this at an enterprise-scale, and we only have a few weeks to deliver!

Thanks

Dave

Gridview, Extra Rows Questions

$
0
0

Hi all,

I've written a function to connect to a SCCM database and create an array with software and versions for a particular machine within a form. My only problem is that the columns and rows are created successfully, but blank extra rows are created (numbers around 50% of the populated rows) during the loop. I suspect this is due to an extra loop being created for each header but I'm not sure why. The form is being written in Powershell studio

function SQL_SCCM_Connection_Machine_Software
{
	param (
		[ValidateNotNull()]
		[Parameter(Mandatory)]
		[string]$machine,
		[ValidateNotNull()]
		[Parameter(Mandatory)]
		[int]$GridNumber
	)
	$GridRow = Get-Variable -Name ("Datagridview" + $GridNumber) -ValueOnly
	cls
	Write-host "Opening a connection to '$SQL_SCCM_Database' on '$SQL_SCCM_Server'"
	$connectionString = "Server=$SQL_SCCM_Server;Database=$SQL_SCCM_Database;Integrated Security=SSPI;"
	$connection = New-Object System.Data.SqlClient.SqlConnection
	$connection.ConnectionString = $connectionString
	$connection.Open()
	$query =
	if ($machine.Length -ge 14)
	{"select distinct v_Add_Remove_Programs.DisplayName0 as 'SoftwareOnMachineA',
                      v_Add_Remove_Programs.Version0 as 'Version'
                      from v_R_System inner join
                     [dbo].[v_Add_Remove_Programs] on v_R_System.ResourceID =  [dbo].[v_Add_Remove_Programs].ResourceID
                     where name0 like '%$machine%' and v_Add_Remove_Programs.DisplayName0 is not null"
	}
	$command = $connection.CreateCommand()
	$command.CommandText = $query
	$result = $command.ExecuteReader()
	$table1 = new-object System.Data.DataTable
	$table1.Load($result)
	$Count = $table1.Rows.Count
	# Close the connection
	$connection.Close()
	$headers = ($table1 | Get-Member | where { $_.membertype -eq "property" }).name
	$headers | Out-GridView -Wait
	$H=0
	foreach ($header in $headers)
	{
		$NewColumn = New-Object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn
		$NewColumn.Name = $header
		$NewColumn.HeaderText = $header
		# Add the Column to the Datagridview
		$GridRow.Columns.Add($NewColumn)
		$i = 0
			foreach ($line in $table1)
			{
				#$line | Get-Member | Out-GridView -Wait
				#$GridRow.Rows.cells[1].Add($line.($headers | select -index 0))
				#$GridRow.Rows.cells[2].Add($line.($headers | select -index 1))
				#$GridRow.DataSource.NewRow()
				$GridRow.Rows.Add()
				$GridRow.item($header, $i).value = $line[$header]
				$i++
			}
		$H++
	}
}

 

Can I filter the Microsoft Security Update report according to my liking?

$
0
0
I already have a set of code and it work perfectly. The problem is the report generated for using Get-MsrcSecurityBulletin is too long. I wanted to filter the output using "server" as keyword. Anyone have an idea on how to filter the report so that it only output everything related with server?

Login script to detect subnet and run script

$
0
0

I need a script to detect the subnets. Then if in these subnets 10.x.1.x to 10.x.254.x place in this group and run this script. I need about 4 diff groups for diff subnents that we have. I have seen the article from the scripting guys that contains this code. I am dealing with 80 subnets or so.


Set objNetwork = CreateObject("Wscript.Network")

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colAdapters = objWMIService.ExecQuery _
    ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled=True")

For Each objAdapter in colAdapters
    For Each strAddress in objAdapter.IPAddress
        arrOctets = Split(strAddress, ".")
        If arrOctets(0) <> "" Then
            strSubnet = arrOctets(0) & "." & arrOctets(1) & "." & arrOctets(2)
            x = 1
            Exit For
        End If
        If x = 1 Then
            Exit For
        End If
    Next
Next

Set colItems = objWMIService.ExecQuery _
    ("Select * From Win32_LogicalDisk Where DeviceID = 'H:'")

If colItems.Count = 0 Then
    Select Case strSubnet
        Case "192.168.1"
            objNetwork.MapNetworkDrive "H:", "\\arizona-fs-01\public"
        Case "192.168.2"
            objNetwork.MapNetworkDrive "H:", "\\newmexico-fs-01\public"
        Case "192.168.3"
            objNetwork.MapNetworkDrive "H:", "\\texas-fs-01\public"
    End Select
End If

Extract AD group members from various domain

$
0
0

Hi,

I would like to extract AD group members from different domains in the same forest. Is there any way we can achieve this? I suspect few of the AD have members from cross domain (within same forest). So need to extract those group members as well.

'How Can I Map a Drive Based on the Computer’s Subnet?' Question

$
0
0
Hey,

In the article on mapping a drive based on a computer's subnet, a brief mention is made about the difficulty of doing this with a PC that has two or more active NICs.  It was mentioned as something that the scripting guys would have to tackle in the future.  Well, there's no time like the present! :-)  (http://www.microsoft.com/technet/scriptcenter/resources/qanda/mar08/hey0304.mspx)

We're trying to deploy this script in our AD domain, but we do have many users with multiple NICs and our tests with these machines have not been positive.  Has anyone had any luck adjusting this script in that kind of circumstance?

Thanks!

John



Printing to PDF via script is printing blank documents

$
0
0

I am trying to use powershell to print each item (.tif files) in a directory as PDF's, while retaining their original file names. I would like this to happen with no user intervention. I am using Microsoft Print to PDF.  

I found the following script which i was planning to modify for my scenario - https://social.technet.microsoft.com/Forums/ie/en-US/04ddfe8c-a07f-4d9b-afd6-04b147f59e28/automating-printing-to-pdf?forum=winserverpowershell

function ConvertTo-PDF {
param(
$TextDocumentPath
)

Add-Type -AssemblyName System.Drawing
$doc = New-Object System.Drawing.Printing.PrintDocument
$doc.DocumentName = $TextDocumentPath
$doc.PrinterSettings = new-Object System.Drawing.Printing.PrinterSettings
$doc.PrinterSettings.PrinterName = 'Microsoft Print to PDF'
$doc.PrinterSettings.PrintToFile = $true
$file=[io.fileinfo]$TextDocumentPath
$pdf= [io.path]::Combine($file.DirectoryName, $file.BaseName) + '.pdf'
$doc.PrinterSettings.PrintFileName = $pdf
$doc.Print()
$doc.Dispose()

However when i do this, it outputs a blank pdf file with the correct name. Any ideas? 

Find AD accounts that will expiry in 31 days

$
0
0

Hi,

I have a PS script that searches for AD user accounts that will expire within 31 days and sends email notification to the users and admins.

Now, I'd like to modify it so it would find all AD accounts that will expiry exactly after 31 days (I'm going to create a scheduled task for it and run it every day)

The line that do "searching" looks like that:

$users = Search-ADAccount -UsersOnly -AccountExpiring -TimeSpan 31:0:0:0.0 -SearchBase "OU=TestOU,DC=clf,DC=internal"

I guess I need to replace -TimeSpan with something else but I'm quite new to scripting so have no idea what that would be :-)

Thanks

How to retrieve full information

$
0
0

Hello,

Certainly very basic question but…. How can I retrieve and display full information of launched commands. Not easy to explain so look at the following example Screenshot :-)

How can I "remove" the three dots and replace them with all the commands at the end of the column ExportedCommands ?

Thanks in advance

Exchange Online: Report Who is Authorized to Send to a Distribution List

$
0
0

Hi guys,

When I try to export the Report Who is Authorized to Send to a Distribution List, I cannot got all the members by run the powershell cmdlet.

Run the cmdlet Get-DistributionGroup “DL Name” | Select Name,AcceptMessagesOnlyFromSendersOrMembers | out-file E:\dl.txt , there cannot get all the members, but "..." instead.

Name                                                                             AcceptMessagesOnlyFromSendersOrMembers                                        
----                                                                             --------------------------------------                                         
365 ALL                                                                          {Managing_Distribution_List, Computer, Yellow River, liyuan...}  

Also I run the cmdlet Get-DistributionGroup “DL Name” | Select Name,AcceptMessagesOnlyFromSendersOrMembers | export-csv E:\dl.csv, there is no separator between the members

#TYPE Selected.System.Management.Automation.PSCustomObject
NameAcceptMessagesOnlyFromSendersOrMembers
365 ALLManaging_Distribution_List Computer Yellow River liyuan SMO-14098ZPJH Sub Business IT Security


So is there any script to export the whole members of the report, and can easily export all the members?

Set-DnsClientServerAddress -Confirm asks twice

$
0
0

When I use "Set-DnsClientServerAddress -Confirm" it always asks for confirmation twice. Answering "yes" to either (or both) results in the desired changes being applied. I only want it to ask for confirmation once. How can I make it ask only once?

The double-ask does not seem to be related to the quantity of ServerAddresses I specify, nor does it seem to be related to the quantity of existing ServerAddresses being changed. Tried on Windows 10 1809, Server 2019 1809, and Server 2016 1607. Tried on local machine and on remote machine using CimSession. I am running as admin. No matter what, -Confirm always prompts twice. I don't want this.

For example:

Set-DnsClientServerAddress -InterfaceIndex 2 -ServerAddresses "192.168.0.1" -Confirm
Viewing all 15028 articles
Browse latest View live


Latest Images

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