Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

click on hyperlink with javascript function call

$
0
0

This is the HTML code with javascript function call inside href.

<a href="javascript:OpenScreen()" onMouseOut="swapImage('imgOpen','imgOpenOff')" onMouseOver="swapImage('imgOpen','imgOpenOn')"><img src="http://test.com/im/butt_open.gif" width=110 height=20 border=0 name="imgOpen"></a>

I tried to use following powershell script to click on it and didn't work.  Could anyone please help how to make it working?

$ie.navigate("URL")
$link=$ie.Document.getElementsByTagName('A') | select-object href="javascript:OpenScreen()"

$link.click()

Thanks in advance!


download file from web on remote pc

$
0
0

The Following script works perfectly on a local computer but issue occurs when it runs on a remote computer.

$machines = Get-Content "c:\Users\metho\Desktop\test.txt"
[ScriptBlock] $script = { 

$url = "http://192.168.1.1/stuff/test.txt"
$target = "C:\Documents and Settings\metho\Desktop\test.txt"

[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$vbnt = New-Object Microsoft.VisualBasic.Devices.Network
$vbnt.DownloadFile($url, $target,"","",$true, 40, $true)

}
$cred = Get-Credential
$sessions = $machines | New-PSSession -Credential $cred
Invoke-Command -ScriptBlock $script -Session $sessions
$sessions | Remove-PSSession

i get the following the error message if i run on a remote pc!

Exception calling "DownloadFile" with "7" argument(s): "The operation has timed out"+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException

i dont know what i am doing wrong, can anyone help?


Job mangles datatypes of returned objects?

$
0
0

A few days ago, one of my PowerShell scripts started returning wrong values. I think it boils down to this example:

# ArrListJob.ps1

$arr = @();
foreach ($i in 1..10) {
	$arr += $i;
}

$obj = New-Object -Type System.Object
Add-Member -InputObject $obj -MemberType NoteProperty -Name Members -Value $arr;
$obj;

When I run this script, everything works fine:

> $foo = .\ArrListJob.ps1> $foo.Members.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array

But when I let this script run via a Job, I get this result:

> Start-Job -FilePath .\ArrListJob.ps1> $bar = Receive-Job Job2> $bar.Members.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     ArrayList                                System.Object

In my real script, I had a loop that wrote the contents of the returned array, but now returns instead "System.Collection.ArrayList". The behaviour changed between 2013-01-02 and 2013-01-03, after installing a few Windows Updates, including fixes for .Net. The script itself was not changed for some time.

Is all this a bug or a feature? I wouldn't expect the Job framework to mangle datatypes. Of course I can fix the handling of the return value in my real script, but then it would break in case I'd use it directly and not via a Job.

One more thing: When returning only the array, i.e. without enclosing it in a object, the correct datatype is kept.

Delete DNSRecords with PowerShell Get-DNSRecord | Remove-DNSObject

$
0
0

Hi Guys,

I have lots of DNS records very old and I want to get rid of them using the powrshell as I have problem getting the DNS Scavenging to work.

I have tried to get all the old DNS A Records by filttering the timestamp of each record, but most of the timestamp records are between 2008/2012 I'm not getting the timestamp to work with years.... Any helppppppppppp

I have tried "TimeStamp<>2008" it also listing all of the records. any help to specify it to particular year?

Get-DnsRecord -Filter "TimeStamp<>0" -RecordType A | where {$_.IPAddress -like "*10.10.*"} | Remove-DNSObject

Insert timestamp along with a string

$
0
0

We are preparing a automation script using EWS .

Requirement : to send a mail to a recipeint with subject containing : <string > + < time it was send >

What i have in hand : i am able to find the property for time it was send ie Datetimesend 

Technical roadblock : I need to insert this property along with a string 

Eg: DC1toDC2+Datetimesend

Even if a solution cannot be provided , please guide me as to what can be done ?

How to open windows firewall ports with powershell

$
0
0

Hi 

Im trying to figure how how to make a Powershell script that opens, multiple firewall ports (incomming). on the local server. (using win2008r2).

any ideas?

best regards

Bjørn

Windows Server 2012 AD-DS can not be configured or uninistalled (Microsoft.Directory.Services.Deployment.DeepTasks.DeepTasks not found)

$
0
0

Good Afternoon everyone,

I am currently trying to promote my 2012 Server to a Domain Controller but when I am at the first step in the setup I get the Error Message

(German, Original Message):

[Bereitstellungskonfiguration] Fehler bei der Bestimmung, ob der Zielserver bereits ein Domänencontroller ist: Der Typ [Microsoft.Directory.Services.Deployment.DeepTasks.DeepTasks] wurde nicht gefunden: Vergewissern Sie sich, dass die Assembly, die diesen Typ enthält, geladen ist.

(Translated to English):

Error while determining, if the Targetserver already is a Domain Controller: The Type [Microsoft.Directory.Services.Deployment.DeepTasks.DeepTasks] was not found: Make sure, that the assembly, that contains this type, is loaded.

Thus I can neither Configure the AD-DS nor deinstall them via Server Manager. Any Help how to fix that problem would be greatly appricieated.

Extracting Event Logs into a CSV file/ txt file or to html page

$
0
0
Hi all,

I am working on a Powershell Script, to extract event logs to a txt file, csv file or even a html page,
although i have a few problems, and i am new to powershell and need to understand some basics aswell.

Requirements -

To exract event id's from multiple servers which read servers from a text file, although how should you list the servers in a text file, the format?

and can someone help me save a log file to a location on the c drive

i have got as far as this below -

Get-eventlog system -newest 30 ¦ where-object {$_.eventid =eq 7036}

this was just trying out powershell which worked but i have tried so many commands and I have not got anywhere.

if anyone can help and have a script i would be most grateful and guide me to get this up and running. thanks in advance

Calling functions from a powershell script

$
0
0

Hello

 

I am aiming to collect data from around 50 SQL Servers from a central server using powershell.

 

I found Chad Millars great tutorial here about how to collect and write data back to a central location...

 

http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx

 

It basically uses two functions, invoke-sqlcmd2 and write-datatable. I downloaded these and called them via my simple powershell script called serverinfo.ps1 here….

 

Invoke-sqlcmd2 -ServerInstance "LAPTOP" -Database DBA_Admin -Query "Select ServerName FROM ServerList" |

foreach-object { $dt = Invoke-SqlCmd2 -ServerInstance $_.ServerName -Database master -InputFile ./serverinfo.sql -As 'DataTable'

Write-DataTable -ServerInstance "LAPTOP" -Database "DBA_Admin" -TableName "ServerInfo" -Data $dt }

 

Now this script runs fine from powershell as long as I dot source the two functions first otherwise I get the usual error message...

The term 'Invoke-sqlcmd2' is not recognized as the name of a cmdlet, function, script file, or operable program.

 

Does anyone know what I need to do so I can run my script from the SQL Agent (or task scheduler) without needing to dot source the two functions first.

Thanks

One application running two processes with same session id

$
0
0

Hi,

Background: Windows 2008 R2, Citrix XenApp 6, publishing desktop via XA

Users connect via Citrix XenApp Desktop to a server, and it only seems to happen with one application at the moment. They run the application, for example xyz.exe, and it works fine, then it will crash/freeze we think as the users aren't letting us know. They then exit out of the application, or so they think and then load it up again and continue to work again.

Need powershell to;

  1. identify when a process of same name has two seperate process id's in the same session id
  2. notify of process on what server via email

Thanks in advance

Enable-PSremoting or winrm qc received error

$
0
0

Hi

I want to enable remote management on Windows 2003 R2. The WinRM service is running but after running winrm qc i received:



and after running in elevated powershell command enable-psremoting -force:



The firewall is disabled. Can some one give a tip what is wrong?

Thanks



New-ADUser and Importing from CSV with Null Fields

$
0
0

Hi,

I am new to Powershell so please forgive me if this is a stupid question.  My starting point was a script I found by HicanNL on http://gallery.technet.microsoft.com/scriptcenter/PowerShell-Create-Active-7e6a3978/view/Discussions to import users into AD via a CSV file.  The intent of this script is to help us build test and demonstration environments quickly.  Each environment what fields we need to popoulate could be different so therefore I am trying to create one master spreadsheet with all the possible columns that New-ADUser supports (as found herehttp://technet.microsoft.com/en-us/library/hh852238).

The problem I am having is that even though the documentation says nulls are allowed for some of the parameters, if I have a null in my spreadsheet (saved as CSV) it doesn't like it.  I guess it sees the parameter in the import and decides that if I have the parameter, I had better have a value for it. For instance, I might want AccountExpirationDate to be set one time and therefore we will put a date in the field, but next time we might want to keep it blank.  I am trying to avoid juggling dozens of templates and modifying the PS1 file each time.

So what is my best method to ignore on a column by column (field by field) on a import by import basis values that may be null?  I inserted the relevant portion of my code below.  Be kind, I am not a developer.

Thanks.

Alan

Import-CSV $newpath | ForEach-Object  { 
    If(!$exists)
    {
      $i++
	  # Needed to import the password to prevent errors since it is plain text in the CSV file.
	  $AccountPasswordSecure = ConvertTo-SecureString $_.AccountPassword -AsPlainText -force
	  #Converts the false/true 0/1 values from the CSV which are seen as a string to boolean which Powershell requires.	
	  $_.UserMustChangePasswordAtLogon = [System.Convert]::ToBoolean("True")
	  $_.UserCannotChangePassword = [System.Convert]::ToBoolean("True")
	  $_.PasswordNeverExpires = [System.Convert]::ToBoolean("True")
	  $_.AllowReversiblePasswordEncryption = [System.Convert]::ToBoolean("True")
	  $_.AccountEnabled = [System.Convert]::ToBoolean("True")
	  $_.SmartcardLogonRequired = [System.Convert]::ToBoolean("True")
	  $_.AccountNotDelegated = [System.Convert]::ToBoolean("True")
	  $_.CompoundIdentitySupported = [System.Convert]::ToBoolean("True")
	  $_.PasswordNotRequired = [System.Convert]::ToBoolean("True")
	  $_.AccountEnabled = [System.Convert]::ToBoolean("True")
	  # OtherAttributes is a Hash Table. This converts the strings in the CSV file to a Hash Table.
	  $OtherAttribuesHash = ConvertFrom-StringData $_.OtherAttributes
	  # The code below maps the column names in the CSV file to the actual parameters names needed for import. 
	  # Blank values will not be imported.
	   New-ADUser `
			-GivenName $_.FirstName `
			-Initials $_.Initials `
			-Surname $_.LastName `
			-Name $_.FullName `
			-DisplayName $_.DisplayName `
			-Description $_.Description `
			-Office $_.Office `
			-OfficePhone $_.OfficePhone `
			-EmailAddress $_.EmailAddress `
			-HomePage $_.WebPage `
			-StreetAddress $_.StreetAddress `
			-POBox $_.POBox `
			-City $_.City `
			-State $_.StateProvince `
			-PostalCode $_.ZIPPostalCode `
			-Country $_.CountryRegion `
			-UserPrincipalName $_.UserLoginName `
			-SamAccountName $_.UserLoginName2000 `
			-AccountPassword $AccountPasswordSecure `
			-ChangePasswordAtLogon $_.UserMustChangePasswordAtLogon `
			-CannotChangePassword $_.UserCannotChangePassword `
			-PasswordNeverExpires $_.PasswordNeverExpires `
			-AllowReversiblePasswordEncryption $_.AllowReversiblePasswordEncryption `
			-Enabled $_.AccountEnabled `
			-SmartcardLogonRequired $_.SmartcardLogonRequired `
			-AccountNotDelegated $_.AccountNotDelegated `
			-KerberosEncryptionType $_.KerberosEncryptionType `
			-CompoundIdentitySupported $_.CompoundIdentitySupported `
			-PasswordNotRequired $_.PasswordNotRequired `
			-AccountExpirationDate $_.AccountExpirationDate `
			-ProfilePath $_.ProfilePath `
			-ScriptPath $_.ScriptPath `
			-HomeDirectory $_.HomeDirectory `
			-HomeDrive $_.HomeDrive `
			-HomePhone $_.HomePhone `
			-MobilePhone $_.MobilePhone `
			-Fax $_.Fax `
			-Title $_.JobTitle `
			-Department $_.Department `
			-Company $_.Company `
			-Manager $_.Manager `
			-Division $_.Division `
			-EmployeeID $_.EmployeeID `
			-EmployeeNumber $_.EmployeeNumber `
			-Organization $_.Organization `
			-OtherAttributes $OtherAttribuesHash `
			-OtherName $_.OtherName `
			-AuthType $_.AuthType `
			-Certificates $_.Certificates `
			-Credential $_.Credential `
			-Instance $_.Instance `
			-LogonWorkstations $_.LogonWorkstations `
			-PassThru $_.PassThru `
			-Path $_.Path `
			-PrincipalsAllowedToDelegateToAccount $_.PrincipalsAllowedToDelegateToAccount `
			-Server $_.Server `
			-ServicePrincipalNames $_.ServicePrincipalNames `
			-TrustedForDelegation $_.TrustedForDelegation `
			-Type $_.Type `
			-Confirm $_.Confirm `
			-WhatIf $_.WhatIf 

      $output | Out-File $log -append
    }
    Else
    {
      "Record skipped as account already exists or other error exists: " + $_.CN | Out-File $log -append
    }
  }


My Ramblings @ http://alanwhitehouse.wordpress.com and My Tweets @ http://www.twitter.com/alanwhitehouse

PowerShell 3 update-help (proxy issues?)

$
0
0

I am running the PowerShell 3.0, as an admin, but update-help is not working. I suspect it does not know that we have an outbound proxy that requires: port, host, username, password. However WinHTTP API apps should grab this from the default credentials. I expected PS to do this.

PS C:\Windows\system32> update-help
update-help : Failed to update Help for the module(s) 'ISE, Microsoft.PowerShell.Management, Microsoft.PowerShell.Utility, CimCmdlets, Microsoft.PowerShell.Diagnostics,
Microsoft.PowerShell.Host, Microsoft.PowerShell.Security, Microsoft.WSMan.Management, PSScheduledJob, PSWorkflow, PSWorkflowUtility, Microsoft.PowerShell.Core' with UI
culture(s) {en-US} : Unable to connect to Help content. Make sure the server is available and then try the command again.
At line:1 char:1
+ update-help
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Update-Help], Exception
    + FullyQualifiedErrorId : UnableToConnect,Microsoft.PowerShell.Commands.UpdateHelpCommand


Dr. YSG

Send email if file is not generated for last 1 hour

$
0
0

Hello ,

Good Morning.

For every half an hour one of our script runs and dump files in one folder called C:\FSFiles as like this

If file is not generated from last one hour there is problem with something so we need to send emails to helpdesk guys.

So what is the bestway to do this ? Can anyone please help me on this.

Thank you.


Diddi

Can I get the objectsecurity property via ADODB query?

$
0
0

Previously, I asked how to check via PoSh on the "Manager can update membership list" setting for security groups.  I was graciously given a workable solution via ADSI.  I was using ADSI to grab the managedObjects for a user and then using ADSI to grab all the group objects from that list followed by a filter process on the manager's update rights. 

I have since discovered the much faster ADODB query process which is much faster, but I'm missing the one property I really need.  I can query for all groups with a particular managedby property:

$adoCommand = New-Object -comObject "ADODB.Command"
$adoConnection = New-Object -comobject "ADODB.Connection"
$adoConnection.Provider = "ADsDSOObject"
$adoConnection.Open("Active Directory Provider")
$adoCommand.ActiveConnection = $adoConnection
$SQLstring = "SELECT Name, distinguishedName, members FROM '$($LDAPaddress)' WHERE objectCategory='group' AND managedBy='$($UserDName)'"
$adoCommand.CommandText = $sqlstring
$adoRecordSet = $adoCommand.Execute()

What I don't know how to do is filter for the groups the manager is allowed to modify without resorting to the ADSI solution (which requires requerying for each group:

$adsiObj = New-Object System.DirectoryServices.DirectorySearcher([adsi]"")
$adsiObj.filter = "(&(objectCategory=Group)(distinguishedName=$($GroupDname)))"
$group = $adsiObj.findone().getdirectoryentry()
$acl = $ADObject.psbase.ObjectSecurity
$acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | Where {$_.IdentityReference -eq $managedBySID}

What I'm wondering is can the objects returned in the ADODB record set have the psbase.ObjectSecurity property?  if so, what additional property do I need to request in the SQL string to get that?  If not, is there a better method?

Thanks!


how to prompt for a pad and chek if it exist

$
0
0

hello guys,

i want to prompt for a path and then chek if that path exist. if it doenst then it needs to ask for a path again.

if the path exist then i want to get a list of the directorys and subdirectorys, (inc filename and filesize etc.\)

im new to powershell,

thnx,

comparison operator over variables

$
0
0

for example :

$Guy ="my name is peter"
$Guy -like"pe*"

how can i do the same where :

$Guy ="my name is peter"

$compareto="pe*"

$Guy -like $compareto

this like want work the same as the first example, because $compareto is an object.

how do i make the compare with an object?

How to place PowerShell exception into a Win Form Text Box?

$
0
0

Greetings,

could you help me with a question?

Basically, I wrote a Win Form in Visual Studio 2010. My application opens powershell and runs a simple script. New-AdUser.....and it gives me an exception in powershell. I am trying to place this exception into a Rich TextBox in my Win Form.

Is there a specific command I could use to place PowerShell output into a rich text box.

So far I am doing the following:

 Process d = new Process();
            d.StartInfo.UseShellExecute = false;
            d.StartInfo.RedirectStandardError = true;
            d.StartInfo = new ProcessStartInfo("powershell.exe", module + "; " + command);
            d.OutputDataReceived += d_OutputDataReceived;
            d.Start();
            
           }

        private void d_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            richTextBox1.Text = e.Data;
        }         The text box doesn't show anything

Recommended method to fix ~/Desktop after relocating Desktop to another disk

$
0
0

Hi,

I relocated the Desktop, Documents, etc to another drive from the system drive using the Explorer GUI. Now when I try to do something like cd ~/Desktop in Powershell it doesn't find it. I think powershell looks for Desktop in C:/Users/<user-name> (assuming C is the system drive) but the relocation removed this directory.

Is there a recommended way to fix this? perhaps by telling Powershell that ~ is somewhere else?

Thanks in advance,

Howard


how can i do to find database files and path in a list of servers?

$
0
0

I try to do this but it does not work

[Array] $servers = "server01", "server02";


foreach($server in $servers) 

    $disks = Get-WmiObject -ComputerName $server -Class Win32_LogicalDisk -Filter "DriveType = 3"; 

    $server = $server.toupper()

    foreach($disk in $disks)
        {

         Get-ChildItem  -include *.ldf,*.mdf | select name  -last 8
         write-out $printout 
}

}

can anybody help me?

Thanks!


Viewing all 2562 articles
Browse latest View live


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