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

when does UpdateID not equal UpdateID for Windows Update searches?

$
0
0

I'm trying to automate some Microsoft updates on Windows 7.  I'm trying to find some already installed updates, then uninstall them.  The weird thing is that I can do it for one KB, but not for another KB. 

I use the same steps for each KB: find it in the installed history, get its historical UpdateID, then use the searcher to locate the specific item again to use with the Uninstall method later.  I am unable to use the Searcher for one of the KBs, even though it is already on my system.

$updater = New-Object -ComObject Microsoft.Update.Session
$searcher = $updater.CreateUpdateSearcher()
$history = $searcher.QueryHistory(1,$searcher.GetTotalHistoryCount()) # retrieve the full history of installed updates
$kbs = ('KB3068708','KB3022345')
foreach ($kb in $kbs) {
    $removable = $history | where {$_.title -match $kb}
    if ($removable -ne $null) {
        $id = $removable.UpdateIdentity.UpdateID
        write-host "$kb found in history with UpdateID=$id"
        $search = 'UpdateID=''' + $removable.UpdateIdentity.UpdateID + ''''
        $removeit = $searcher.Search($search)
        if ($removeit.Updates.Count -gt 0) {
            write-host "Success!  Able to search the update based on its historical updateIdentity.UpdateID value"
        } else {
            write-host "Failure!  UNable to search the update based on its historical updateIdentity.UpdateID value"
        }
    }
}

I get these results:

KB3068708 found in history with UpdateID=0cd9efd9-d371-4e7d-8381-15ae5b55ea79
Success!  Able to search the update based on its historical updateIdentity.UpdateID value
KB3022345 found in history with UpdateID=94ec92df-8687-4f9e-acca-2c4ac8bf3b19
Failure!  UNable to search the update based on its historical updateIdentity.UpdateID value
What am I doing wrong here?

Add User From a domain to another Domain

$
0
0

Hi!

I have two domains (dom1 and dom2). How to add an user from the dom1 to a group in the dom2 using ADSI.

And How can I verified if the user is already in the group?

I use powershell v2

Thank You

Using if statements in Powershell for search Robocopy Results

$
0
0
 

Hi,

We currently have a script that Purges a folder structure apart from 3 files and a folder.

 $Result = Robocopy "source" "target" *.* /NP /V /E /R:1 /W:1 /PURGE /XF File1 File2 File3 /XD Folder 

this works as expected, However when then checking if the robocopy was successful

 if ($result -gt 7){"fail"} 

The result is always a failure. I believe it has something to do with the exclusion of files and folders from a purge but I am unsure.
 
Without having the exlusion the if statement works for a purge and without (useful when running jobs and so cannot see the lastexitcode)
 
Does anyone know why this behaviour occurs and if there is anyway of getting round it
 

Thanks
 
tom
 


 

Changing the number to indian format

$
0
0

Hi Guys,

I got a requirement. I have checked in google and found no results. The requirement is We have to fetch the data from csv file to sql database. In that I will get some values in this format "29707639.56". But we have to insert the data in this format "2,97,07,639" .Could you guys help me out!! 


Naveen Basati

IE9 - InPrivate With Multiple Tabs

$
0
0

Guys I need your help, desperately.

I have a need to open 2 webpages on a kiosk type machine (not actually a kiosk) it only runs IE but I want the pages to open using the InPrivate mode. I have got so far and now drawing a blank. I got a few scripts to almost do what I wanted and I have pasted the content below.

This VBS will open 2 separate windows both InPrivate

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run ("iexplore -private http://www.google.com")
WshShell.Run ("iexplore -private http://www.yahoo.com")

 This JS will open both pages in 1 windows but not InPrivate

var navOpenInBackgroundTab = 0x1000;
var oIE = new ActiveXObject("InternetExplorer.Application");
oIE.Navigate2("http://www.google.com");
oIE.Navigate2("http://www.yahoo.com", navOpenInBackgroundTab);
oIE.Visible = true;

And this JS opens 2 windows to the pages I want but not in the same window

var navOpenInBackgroundTab = 0x1000;
var oShell = new ActiveXObject("WScript.Shell");
oShell.run("\"%ProgramFiles%\\Internet Explorer\\iexplore\" -private http://www.google.com");
oShell.run("\"%ProgramFiles%\\Internet Explorer\\iexplore\" -private http://www.yahoo.com");

So as you can see I'm not quite where I want to get to. In addition to the above I have researched forcing IE into InPrivate using the reg keys in PrivacIE branch but this doesn't work, IE never opens iInPriave when making these setting.

Help please!!!!!

Cheers


Import AD groups from csv and export their members

$
0
0

Hello All,

Having a bit of an issue doing this with bulk import. No issues with running Get-ADGroupMember on a single group but with import... I want to pull my hair out. Not sure if I need to create a custom object or what but I need to import a csv with say 100 groups and export their members. The issue that I am having is that on the export... I need to have the group name so I know what group theyre members of. Also, I need to get the nested groups (not a recursive to see the nested groups members but the group object itself) as well as any orphaned SIDs. 

I have been researching and testing for weeks... at my wits end.. please help!

PSRemoting from Work Group (Non Domain) machine to Domain joined Machine

$
0
0

Hi Team,

I have 2 machines 

M1 - Domain Joined and M2 - Work Group Machine

On Domain Joined Machines (M2) is have enabled psremoting using following method

1. On domain machine (M1) i have added value * in WSMan:\localhost\client\Trustedhost 

2. Enabled-psremoting 

Now,

I am trying to perform "Enter-PSsesion" cmdlet from workgroup (M2 )machine to domain joined (M1 )machines and getting following error 

Enter-Pssession -computername m1.domain.com -credential domain\username 

Error - 

Connectingto remote server M1 failed with the following error message :TheWinRM client cannot process the request.If the authentication scheme is different from Kerberos, or if the client
computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to theTrustedHosts configuration setting.Use winrm.cmd to configure TrustedHosts.Note that computers in the TrustedHosts
list might not be authenticated.You can get more information about that by running the following command: winrm help
config.For more information, see the about_Remote_Troubleshooting Help topic.

Please Suggest ....... 

Powershell - Process Redirect - Polling

$
0
0

Hi

I found a number of articles on running processes and BAT files and capturing the output and errors, e.g.

http://www.chinabtp.com/captured-output-of-command-run-by-powershell-is-sometimes-incomplete/
http://stackoverflow.com/questions/24370814/how-to-capture-process-output-asynchronously-in-powershell

So I created a test function below and it "works"
However I wanted to have control over the display of the output, i.e. close to real time. According to the doco the event gets fired for each newline, my tests indicate otherwise.
i.e. the script may run for a long time and have 1000s of lines of output..

I did a test where I told the BAT file to sleep. However the results where not as expected.
There was a delay until the first output occurred, then a further delay which could be accounted for due to the sleep.

https://msdn.microsoft.com/en-us/library/microsoft.powershell.utility.activities.registerobjectevent_methods(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/microsoft.powershell.utility.activities.registerobjectevent_members(v=vs.85).aspx

Don't help because there are poorly documented, e.g. MaxtriggerCount, provides access to maxtriggercount, none of the items are actually described by function.

The C# process has ReadToEnd() but this does not apply to Powershell

So the question :

>> Is there a way for me fetch the output event data, say in the 1s while loop ?

SBS_Logger justs adds the timestamp

Function SBS_RunAProcess
{
[CmdletBinding()]
 param(
 		[Parameter(Mandatory = $True)]
       [String]$Label )

		# Setup stdin\stdout redirection
		$StartInfo = New-Object System.Diagnostics.ProcessStartInfo -Property @{
			FileName = "F:\ScriptWork\helloworld.bat"
			Arguments = $Label
			UseShellExecute = $false
			RedirectStandardOutput = $true
			RedirectStandardError = $true
		}
		# Create new process
		$Process = New-Object System.Diagnostics.Process
		# Assign previously created StartInfo properties
		$Process.StartInfo = $StartInfo
		# Register Object Events for stdin\stdout reading
		$OutEvent = Register-ObjectEvent -InputObject $Process -EventName OutputDataReceived -Action {

		SBS_Logger $Event.SourceEventArgs.Data
		}
		$ErrEvent = Register-ObjectEvent -InputObject $Process -EventName ErrorDataReceived -Action {

		SBS_Logger $Event.SourceEventArgs.Data
		}
		# Start process
		[void]$Process.Start()
		# Begin reading stdin\stdout
		$Process.BeginOutputReadLine()
		$Process.BeginErrorReadLine()
		# Do something else while events are firing
		do
		{
			#Write-Host 'Still alive!' -ForegroundColor Green
			Start-Sleep -Seconds 1
		}
		while (!$Process.HasExited)
		# Unregister events
		$OutEvent.Name, $ErrEvent.Name |
		ForEach-Object {Unregister-Event -SourceIdentifier $_}
 }
BAT Content

@echo off
echo "hello world from a BAT file"
echo "args where %1%"
rem timeout /t 10 /nobreak > NUL
SET

===

2015-09-03 14:04:00 Task test_bat running
2015-09-03 14:04:01 "hello world from a BAT file"
2015-09-03 14:04:01 "args where greg"
2015-09-03 14:04:01 ALLUSERSPROFILE=C:\ProgramData
2015-09-03 14:04:01 APPDATA=C:\Users\build\AppData\Roaming


=====================
BAT Content

echo off
echo "hello world from a BAT file"
echo "args where %1%"
timeout /t 10 /nobreak > NUL
SET

===

2015-09-03 14:08:43 Task test_bat running
2015-09-03 14:08:54 "hello world from a BAT file"  <= 9s delay
2015-09-03 14:08:54 "args where greg"
2015-09-03 14:09:03 ALLUSERSPROFILE=C:\ProgramData <= 9s delay



Microsoft Print to PDF

$
0
0
How can I designate name & location of the PDF?

Get Windows Power Options (Sleep Mode) through Script

$
0
0

I am facing issue where in many of the servers go into sleep mode after 3 hours of idle state. I am not sure on how many servers this Sleep Mode setting is applied and wants to find it out on all the list of servers.

Can someone please help me with a script which can extract the "Sleep Mode" settings in Windows Power Options in Tabular form or formatted Excel format.

Requirement: Script to take input (computer names) from a text/CSV file and output to Excel/CSV file.

Thank you very much in advance !!

Regards

Amit Rao

Powershell script export of users with filterd member off groups

$
0
0

Hello Guys,

I am making a Powershell script to make an export of users in a specific OU. From the export i want to know:

- Accountname

- Emailaddres

- Whencreated

- Account enabled

- Member of groups

     With the member of gropus i only want to see the groups that starts with: GG_

I hope some one can help me

Need to block USB's for all Computers

$
0
0

I need to block or Unblock USB devices using scripting

Thanks in Advance..

NTRao

Change all mailbox owners in an OU 's ReadOnly Access to FullAccess

$
0
0

I've recently been tasked with changing all owners of shared mailboxes in two Organizational Unit's permissions from ReadAccess to FullAccess. Is there a way to do this? The below obviously does not work since -OrganizationalUnit will not work with get-mailboxpermission, but just trying to give an idea of close to what I'm trying to accomplish. Any help would be much appreciated.

$ExistingReadPerms = Get-mailboxpermission -OrganizationalUnit "Ou/ConferenceRooms" -resultsize "unlimited" | ? {$_.AccessRights -eq 'ReadPermissions'}

Foreach ($Perm in $ExistingReadPerms)

{

Add-mailboxPermission -OrganizationalUnit"Ou/ConferenceRooms" -resultsize "unlimited" -AccessRights FullAccess -user $Perm.User

}

VBScript to parse pattern in file. Find 1st, then Find 2nd, then start over.

$
0
0

Need to find path, then modified from this block of text. Finding the first Path. Then the next modified. Add those to array then find the next path and modified. In PowerShell I would use a Join, but I have to do this one in VBS.  Any help would be wonderful!

Example Text:

Path = c:\temp\EDIarchive\ARROW\ARROW.7z
Type = 7z
Method = LZMA
Solid = +
Blocks = 1
Physical Size = 25061
Headers Size = 1094

----------
Path = ARROW_810_7613035_2015Jan29 - Copy.TXT
Size = 3389
Packed Size = 23967
Modified = 2015-01-29 21:05:37
Attributes = ....A
CRC = 5C89B76B
Encrypted = -
Method = LZMA:1536k
Block = 0

Path = ARROW_810_7613035_2015Jan29.TXT
Size = 3389
Packed Size =
Modified = 2015-01-29 21:05:37
Attributes = ....A
CRC = 5C89B76B
Encrypted = -
Method = LZMA:1536k
Block = 0

Path = ARROW_810_7625589_2015Jan30 - Copy.TXT
Size = 3371
Packed Size =
Modified = 2015-01-30 16:16:17
Attributes = ....A
CRC = 040A5D3D
Encrypted = -
Method = LZMA:1536k
Block = 0


Andrew Beller III

Directory tree

$
0
0

How can I get a directory listing of directories and sub-directories using a batch file but I want to exclude the directory name. I've tried the following 

dir /s/b/o:n/a:d > Listings.txt 

but I seem to still get the directory path included


unpin Edge and cortana from startmenu and taskbar

$
0
0

hi all

is it posible to unpin Windows 10 Edge from taskbar and startmenu?


Chris

PowerShell stop windows service

$
0
0

Hi all,

I use a PowerShell script to stop a service. However, when the service doesn't stop within 30 seconds I get the message:

--> "The service did not respond to the start or control request in a timely fashion"

I know that I can adjust the timeout via the registry (ServicePipeTimeout), but I was wondering if it's possible to write the script without having to change the registry.

EDIT: I actually changed the setting on one of the servers where it occurs and this doesn't seem to have any effect.

Script (sorry for not adding all param settings):

# Step 1: Stop service.

# Get the System.ServiceProcess.ServiceController object and the WMI WIN32_Service object.

$targetAosServiceObject=(get-service-ComputerName${env:computername}-Name$targetAosServiceName)

$targetAosServiceWmiObject=(Get-WmiObject-computer${env:computername}Win32_Service-Filter"Name='$targetAosServiceName'")

if($targetAosServiceObject.status-eq'Running')# if the AOS is running

{

Write-Host"Stopping AOS$($targetServerInstanceName)."

$targetAosServiceObject|set-service-StartupType'Disabled'# Disable the service to prevent automatic restart.

$targetAosServiceObject.Stop()|out-null# Stop the service, but return immediately.

$targetAosServiceObject.WaitForStatus('Stopped')# Wait for the service to completely stop.

$targetAosServiceObject.Refresh()# Refresh the current status before checking the status condition.

Write-Host"AOS$($targetServerInstanceName)stopped."

}

else

{

Write-Host"AOS$($targetServerInstanceName)was already stopped."

}

The script will wait for the service to stop, if it stops within 30 seconds.

It seems that when starting the service, even when that takes longer than 30 seconds, it doesn't throw this message.

Thanks in advance.

KR,

Dieter

WMI Query to return FreeSpace, Drive name and Size of disk in Windows server

$
0
0

H All,

I am executing below wmi query to get the disk information from windows server.

Select Name, FreeSpace, Size from Win32_LogicalDisk

The output i am getting is a xml file.

What we are expecting is the output of wmi query to be below. Can this be achieved.

"53142114304|C:|110100705280|"

"387322912768|D:|543049400320|"

Or is there an script to achieve this.

Any help is appreciated.

Thanks and Regards
Riyas


$comment, net localgroup

$
0
0

Hy Guys,

I want to write a net localgroup or net group script which can export server admin comment field to csv, from .csv server list.

I found a sript which can export Member field, but it can't export comment.

Can you help for me?

Here $member script:

#>
[CmdletBinding()]
Param(
    [Parameter(    ValueFromPipeline=$true,
                ValueFromPipelineByPropertyName=$true
                )]
    [string[]]
    $ComputerName = $env:ComputerName,
 
    [Parameter()]
    [string]
    $LocalGroupName = "Administrators",
 
    [Parameter()]
    [string]
    $OutputDir = "c:\temp"
)
 
Begin {
 
    $OutputFile = Join-Path $OutputDir "LocalGroupMembers.csv"
    Write-Verbose "Script will write the output to $OutputFile folder"
    Add-Content -Path $OutPutFile -Value "ComputerName, LocalGroupName, Status, MemberType, MemberDomain, MemberName"
}
 
Process {
    ForEach($Computer in $ComputerName) {
        Write-host "Working on $Computer"
        If(!(Test-Connection -ComputerName $Computer -Count 1 -Quiet)) {
            Write-Verbose "$Computer is offline. Proceeding with next computer"
            Add-Content -Path $OutputFile -Value "$Computer,$LocalGroupName,Offline"
            Continue
        } else {
            Write-Verbose "Working on $computer"
            try {
                $group = [ADSI]"WinNT://$Computer/$LocalGroupName"
                $members = @($group.Invoke("Members"))
                Write-Verbose "Successfully queries the members of $computer"
                if(!$members) {
                    Add-Content -Path $OutputFile -Value "$Computer,$LocalGroupName,NoMembersFound"
                    Write-Verbose "No members found in the group"
                    continue
                }
            }        
            catch {
                Write-Verbose "Failed to query the members of $computer"
                Add-Content -Path $OutputFile -Value "$Computer,,FailedToQuery"
                Continue
            }
            foreach($member in $members) {
                try {
                    $MemberName = $member.GetType().Invokemember("Name","GetProperty",$null,$member,$null)
                    $MemberType = $member.GetType().Invokemember("Class","GetProperty",$null,$member,$null)
                    $MemberPath = $member.GetType().Invokemember("ADSPath","GetProperty",$null,$member,$null)
                    $MemberDomain = $null
                    if($MemberPath -match "^Winnt\:\/\/(?<domainName>\S+)\/(?<CompName>\S+)\/") {
                        if($MemberType -eq "User") {
                            $MemberType = "LocalUser"
                        } elseif($MemberType -eq "Group"){
                            $MemberType = "LocalGroup"
                        }
                        $MemberDomain = $matches["CompName"]
 
                    } elseif($MemberPath -match "^WinNT\:\/\/(?<domainname>\S+)/") {
                        if($MemberType -eq "User") {
                            $MemberType = "DomainUser"
                        } elseif($MemberType -eq "Group"){
                            $MemberType = "DomainGroup"
                        }
                        $MemberDomain = $matches["domainname"]
 
                    } else {
                        $MemberType = "Unknown"
                        $MemberDomain = "Unknown"
                    }
                Add-Content -Path $OutPutFile -Value "$Computer, $LocalGroupName, SUCCESS, $MemberType, $MemberDomain, $MemberName"
                } catch {
                    Write-Verbose "failed to query details of a member. Details $_"
                    Add-Content -Path $OutputFile -Value "$Computer,,FailedQueryMember"
                }
 
            } 
        }
 
    }
 
}
End {}

Get User attribute "enabled"

$
0
0

Hi,

I want to querry AD accounts if they anbaled or not.


$vOut

+=Get-ADUser-Identity$_-Propertiesdepartment,company,Name,Enabled|Select-ObjectName,Company,$Datum,$Name,Enabled


The querry is working so far but I am not confident with the result

Their are quiet a few users for which I have an value, but their are to much users who do not have a value for "enabled

I am thinking this is no PS problem, I think this has something to do with the replication of AD

Viewing all 15028 articles
Browse latest View live


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