Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

"InternetExplorer.Application" COM object event caching

$
0
0

Hi All

At vbs language, the WSCript.CreateObject method allowed to set as second parameter a "preffix" for defining event triggered functions associated to the COM object. For instance, for the "InternetExplorer.Application":

Set oIE = WScript.CreateObject("InternetExplorer.Application", "eventsIE_")

Sub eventsIE_NavigateComplete2(pDisp,URL)

....

End Sub

At VBS other aternative was the WScript.ConnectObject method

In powershell, the new-object method does not allow this parameter.

How is it possible to catch COM associated events and launch a given Function in powershell language?

If that´s not possible and I cannot catch the navigateComplete2 event, how may I check from PS code that the navigation to a given URL has been finished by querying the "InternetExplorer.Application" COM object?

Than you so much in adance


Do not continue until a file exists in powershell

$
0
0

Hi,

I was wondering if there is a method in powershell to get it to 

continually check whether a file exists and do not progress until it finds it.

i.e

DO WHILE  

c:\flag.txt NOT EXISTS

Wait 10 seconds

END

<Next command >

So that the <next Command> section is only executed once it finds the file c:\flag.txt

Is this possible?

Thanks,

Zoe

Could use help with writing a script

$
0
0

Hi,

I'm sure you've all heard this before..but I am very new to Powershell and am struggling with writing a script that will add an attribute to a security group - based on a specific character.

I have several group names that start with a '$' and I would like to hide all of those from the GAL.  I am trying to do this in the AD module, without the Exchange plugins.  Our environment is AD - Azure - O365.

IF anyone has a script that would help with that, that would be great.  

Any help is greatly appreciated.

Thank you in advance.

Karl

How to display only error data for Trust verification.

$
0
0

Hi,

I run the following on a Domain Controller which produces blocks of output like the following after the code for each NlTest performed against a Trust. The goal is to just display the errors, so I want to filter on 'Trusted DC Connection Status Status' and determine when not equal to success, then display the 'block' of output around the error, as demonstrated below in the FlyByNite.local trust error.  Suggestions on how to do this?

$DateTime      = Get-Date -format MMddyy-hhmmss
$DomainInfo    = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$TrustsOutput  = "C:\MyReports\$($DomainInfo.Name)TrustVerification$($DateTime).txt"

$AllTrusts = Get-AdTrust -Filter * | Sort Direction

Foreach ($Trust in $AllTrusts)
  {
 "Trust $($Trust.Name)" | out-file -FilePath $TrustsOutput -Append

cmd /c "nltest /Server:$($env:ComputerName) /SC_Verify:$($Trust.Name)" | out-file -FilePath $TrustsOutput -Append
     }


Trust Acme.local
Flags: b0 HAS_IP  HAS_TIMESERV
Trusted DC Name \\SERVER-AD.Acme.local
Trusted DC Connection Status Status = 0 0x0 NERR_Success
Trust Verification Status = 0 0x0 NERR_Success
The command completed successfully


Trust FlyByNite.local
Flags: 80
Trusted DC Name  
Trusted DC Connection Status Status = 1311 0x51f ERROR_NO_LOGON_SERVERS
Trust Verification Status = 1311 0x51f ERROR_NO_LOGON_SERVERS
The command completed successfully


Thanks for your help! SdeDot

Remote Management of Windows Deployment Services (WDS)

$
0
0

Hi

I am trying to manage WDS running on Server 2012 R2 from a Windows 10 client using PowerShell.

Remotely using PowerShell to run non-WDS commands works fine, running WDS commands on the local server also works fine, however, a simple Get-WdsClient command returns 'The operation being requested was not performed because the user has not been authenticated' when run remotely, same problem with other WDS commands (when run locally they work fine).

Does anyone know how to resolve this?

Thanks

Attempting to get ACL reports but I ran into the dreaded 260 character limitation, and have format issues....

$
0
0

I want to generate a report file in .csv format of a portion of our file server.  So I have attempted stuff like this:

C:\admin> get-childitem "c:\admin" | Get-Acl

The above works but I want to put into a .csv and only select certain columns so I did this;

PS C:\admin> get-childitem "c:\admin" | Get-Acl | FL -property path,access >> c:\admin\report.csv

But the output for the access property is not what I wanted, and its like the FL command changed it. 

Then I have to deal with the 260 character limit... so I decided to try and use AlphaFS https://github.com/alphaleonis/AlphaFS.

I have used it successfully to copy and delete stuff but have never tried to enumerate ACLs.  The issue I am having is it does not seem to be able to use a recuse function.  

[Alphaleonis.Win32.Filesystem.Directory]::GetAccessControl($LongDirectory)

I really don't care the methoedolgy in how I do this but would prefer to stick with powershell.  Anybody have any things that work for them that they would like to share?

Thanks!

DL group members update skip not found users in directory

$
0
0

Hi,

Below script using for DL - distribution list group updates. Script updates are quite good, however if any user not found in directory, script will skip entire DL to update further its members instead of that particular user skip. 

Foreach ($Group in(Import-csv "D:\script-users\DL\DL_30May02.csv"))

{$Members=$group.Members.split(";");update-distributiongroupmember -identity $Group.samAccountname -Members $Members -confirm:$false}

write-host "Members updates are completed"

Can any parameter to include to skip only that particular user(not found in directory) and do the DL updates properly 

Please help


MD

failover cluster error event id 1254, 1205 & 1069

$
0
0

Hi,

One of windows 2012 failover cluster throwing this error event ids:-

1254, 1205 & 1069

cluster resource is still failed, it cannot bring online from offline status.

What could be the reason for this offline cluster resource issue?


MD


Request New Certificate from CA, According to user template, Execute in logon Script

$
0
0

Hello There

On my company I can request a new certificate from CA (via MMC/Certificate/Personal) according to the user template that my windows team was provide to me, The big problem is that we have a 2000 workers on the company and we want to make it automatic procedure.

How can i do it on automatic way, that every time that user logon to his personal computer, in the logon script a new certificate will enroll for him, so the simple user will not know that certificate is provide for him.

Our goal in the company is to change all our authorization from HTTP to HTTPS via SSL protocol.

Thanks

Aviv Cohen

Using WorkFlow To Remember State After Rebooting Machine

$
0
0

I am setting up a powershell script that needs to restart, login as the last user that ran the script and re-run the script from the last place it left off.

I can figure out the rest in time but I am stuck in the part where I get it to remember the last save state. I was looking into workflows but when I to test it using something like:

workflow SaveValues {
Write-Output "Current Value for loop:"
if ($i -eq $Null){Write-Output "Nothing`n"}
if ($i -ne $Null){Write-Output "$i`n"}
Start-Sleep -Seconds 2
for ($i=1; $i -le 1000; $i++){
  Checkpoint-Workflow
  Write-Output "Test $i"
}
}

workflow SaveValues2 {
Write-Output "Current Value:"
if ($i -eq $Null){Write-Output "Nothing`n"}
if ($i -ne $Null){Write-Output "$i`n"}
Start-Sleep -Seconds 2
Write-Output ($i = "A Value!")
Checkpoint-Workflow
}

The Values are always reset at the end, and if I interrupt the task it does not save at the last value for $i that I cut the script in but goes back to being null like when your run a value inside a function.

I am fairly new at workflows and have practice in normal PowerShell scripts. I have looked up scripting guy and other people explaining workflows and it seems pretty straightforward and I think I can use it to save the state from the script when I restart the machine but I guess I don't get why when I tell it to save state it doesn't just save every value that is currently being used in the workflow when I rerun it.

UpTimeReports Script Help

$
0
0

As per pulling off a N00B move and making adjustments directly to my script in notepad without saving a separate test version - I screwed up my script and I can't quite seem to figure out what I deleted. I had everything working before and can't figure out what in the world I did.

I was going to add the $TimeStamp variable in order to generate a date oriented naming convention for the .csv file and apparently during that process I accidentally removed something else and I have NO IDEA what it was! I either commented something out or accidentally deleted another element... or both! :( -.- Previously I was able to use this and export a CSV with all of the information set below. Now, I keep getting an error message about "an empty pipeline is not allowed" on line 58. Maybe having another set of eyes on will help. Thanks everyone!

[cmdletbinding()]
Param ( #Define a Mandatory name input
[Parameter(
ValueFromPipeline=$true,
ValueFromPipelinebyPropertyName=$true,
Position=0)]
[Alias('Computer', 'ComputerName', 'Server', '__ServerName')]
[string[]]$name = $ENV:Computername,
[Parameter(Position=1)]
[string]$progress = "Yes"
)
Process	{
        ForEach ($computer in $name) {
	#$TimeStamp = Get-date -Format o |foreach {$_ -replace ":". "."}
        #$computerName = $_

        If (Test-Connection -ComputerName $computer -Count 1 -Quiet) {

                $uptime = Get-WmiObject Win32_OperatingSystem -ComputerName $computer
                $bootTime = $uptime.ConvertToDateTime($uptime.LastBootUpTime)
                $elapsedTime = (Get-Date) - $bootTime

	$props = @{
               	ComputerName = $computer
                BootTime = $bootTime
                ElapsedTime = '{0:00} Days, {1:00} Hours, {2:00} Minutes, {3:00} Seconds' -f $elapsedTime.Days, $elapsedTime.Hours, $elapsedTime.Minutes, $elapsedTime.Seconds
        }

        New-Object PsObject -Property $props
    }
        Else {
            	$props = @{
        	ComputerName = $computer
       		BootTime = 'ERROR - Did not reply to ping'
        	ElapsedTime = 'N/A'
             }
	New-Object PsObject -Property $props
         }
    } | Sort ComputerName | Select ComputerName,BootTime,ElapsedTime | Export-Csv .\$TimeStamp +"ServerUpTime.csv" -NoTypeInformation -Force
}


Evaluate XML without writing and reading back from a file

$
0
0

I'm trying to use Powershell to analyze the Group Policies on my domain. Get-GPOreport returns all the settings of a policy in xml format. This looks like it may be useful.

However, to analyze the GPO contents, I have to output all 126 GP objects to a file, then read each one into an xml object using get-content. Is there any way to skip the step of writing to a file and then reading the file back again?

for example, instead of:

Get-GPOreport -name GPOxxx -reporttype xml -path c:\temp\gpoxxx.xml
[xml]$GPContent = get-content c:\temp\gpoxxx
#examine values of GPO, for example:
$GPContent.Computer.Enabled 

How can I do this without writing the file and reading it back? The following does not work...

[xml]$GPContent = Get-GPOreport -name GPOxxx -reporttype xml

$GPContent.Computer.Enabled 




Disabling list of users and other needs in powershell

$
0
0

Hi hoping someone would be able to assist. Im having difficulties creating a powershell that would allow me to do the following with a list of users based on username on two domains: Disable account, change description . Any help would be great

I am not sure what to add to allow for multiple domains

In the future I will try and add: copy managers name and export information to text file

Import-Module ActiveDirectory
$Users = Import-csv c:\Test\Users.csv
foreach($User in $Users){
Set-ADUser $User.SamAccountName -Description $User.NewDescription
Disable-ADAccount -Identity $User.samaccountname
Write-Host "Completed: " $user
}
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 





How do I get PSRemoteRegistry to work from my Prod workstation when trying to write a scipt pointing to my Tst domain.

$
0
0
I'm writing a script that uses PSRemoteRegistry to access servers on our Test domain (TST\) from my workstation in our prod domain (PROD\). I usually launch Powershell ISE with a runas using my TST\ admin account for this. The problem is that if I do a Get-Modules -Listavailable it says that PSRemoteRegistry is Test-ElevatedShell. If I launch Powershel ISE as Run As Administrator (my PROD/ account), it shows the functions that are in the module. How do I get around this or make this work ? My last resort will be to RDP to a VM in the TST\ domain and work off of that.

To Display only Date after reducing few number of days

$
0
0

Hi,

I am currently in a requirement where i need to run a script which itself calcualtes 90 days lesser to the currentdate and executes the script. My script is absolutely fine, but it runs a bit awkward when i pass on the date through a variable. If I pass the date manually in format MM/DD/YYYY. The script gives me desired output.

Example:

If I am running the script on today, i.e. 7/7/2016, then 90 days lesser to today is 4/8/2016(MM/DD/YYYY). Now i used below command to get that:

$a = (Get-Date).AddDays(-90)

Output: 08 April 2016 17:48:55

But, I don't want the Time which is getting displayed and one more condition is i want it in the format MM/DD/YYYY

Example in this case: 04/08/2016

This is what output i should see, i mean $a should contain 04/08/2016 format Date.


Dynamic Where-Object Filter

$
0
0

I'm trying to use a dynamic where-object filter by building it and assigning it to a variable and then using that variable, something like the following:

$filter = "`$_.thing -match `"criteria`""

get-thing $things | ? {$filter}

But this fails to match, whereas the following matches:

get-thing $things | ? {$_.thing -match "criteria"}

What am I missing?

When I look at $filter after the assignment above, it looks exactly like what's in the curly brackets in the second get-thing call.

I want to be able to do this because there may be multiple criteria and I need to dynamically add -or clauses. If there's a better way, please let me know what that is.

Thanks.

installedOn property missing from get-wmiobject win32_quickfixengineering

$
0
0

Hi!

I'm trying to retrieve the installed date for patches but it seems that powershell get-wmiobject win32_quickfixengineering is not showing the installedOn value while wmic qfe list full shows the installedon value.

I'm not familar with wmi console... is there any workaround for this?

 

How to Use muliple lines input from richtextbox/text box of pirmalforms

$
0
0

HI All,

I am trying to create a computer information tool with pirmal form.

1.I Richtextbox to Input the computer name

2. Multiple buttons (Each for differenct functions like  button1 for ping button two for uptime...ad so on.)

3. Richtextbox2 as an output.

Richtext box is taking only single computer name as the input even if i have typed two computer names line by line.

my question is how to use the multiple lines as different servernames.

any help will be much appreciated.

EX

function Get-PCUptime {
$computers = ($richtextbox1.text)

 
foreach ($computer in $computers)

{
$s = uptime $computer | out-string

$richtextbox2.text = $s
}

}


$array.remove not working as expected

$
0
0

$array =New-ObjectSystem.Collections.Generic.List[System.Object]

$array.Add("aa")

$array.Add("bb")

$array.Add("aa")

$array1 = $array |sort -uniq

switch ($array1[-2]){

"aa" {$array1.Remove("aa")}

...

}

The debugger is entering the correct switch option, passing through remove but is not actually removing the element from array .

Script not excluding users from -NOTLIKE groups

$
0
0

Hi all,

   I am not good in PS, looking for little help from here.

I am trying to get all users who is member of one group stp but not like in stp-pw group from two OUs. Queries is working fine, but it is not exluding users from stp-pw group.

here is my script.

#==================================================================
$OU=@('OU=Microsoft,OU=Users,OU=HQ,DC=MS,DC=fl,DC=com','OU=Contract,OU=Users,OU=HQ,DC=MS,DC=fl,DC=com')

$ous=$ou | foreach  { get-aduser -searchbase $_ -Properties samaccountname, name, office -Filter { office -like "*seattle*" } | select samaccountname, name, office} #| Export-Csv c:\da\output.csv


$WithSTPGrp =  foreach ($user in $ous.samaccountname) { get-aduser $user -Properties memberof,name,samaccountname  | where  memberof -like "*stp*" | where memberof -notLike “*stp-pw-*” |  select name,samaccountname }


$WithSTPGrp | Export-Csv 'c:\da\output.csv' -NoTypeInformation

#==================================================================

thx in advance


orion

Viewing all 21975 articles
Browse latest View live


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