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

Internet Explorer COM Automation Not Working

$
0
0

I've been searching for a solution to this for a while and I'm stunned and embarrassed I haven't found more helpful pages with information how to solve this problem for myself.

I have a few different scripts that spawn an instance of IE, navigate to the page, then update and click elements.  They work fine with IE 8, but nothing newer.  

$ie = New-Object -comobject InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate($URL)


This works fine.  I can type $ie.document | gm at the console and see getElementById, getElementsByClassName, etc in the list of methods and properties, but if I try to access them I get an error:

Cannot find an overload for "getElementsByClassName" and the argument count: "1".
At line:1 char:36
+ $ie.document.getElementsByClassName <<<< ("input")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

I found this link:

http://stackoverflow.com/questions/17924770/how-can-i-translate-or-run-a-vbscript-function-inside-a-ps1-file

That gets me a little bit further:

$EmailField = [System.__ComObject].InvokeMember("getElementsByClassName",[System.Reflection.BindingFlags]::InvokeMethod, $null, $ie.document,"email")


If I output $EmailField I get a long list of properties that includes:

type                         : email
value                        :
name                         : email

But when I try to edit $EmailField, I get another error:

PS C:\Users\user> $EmailField.value
PS C:\Users\user> $EmailField.type
PS C:\Users\user> $EmailField.name
PS C:\Users\user> $EmailField.value = "email@email.com"
Property 'value' cannot be found on this object; make sure it exists and is settable.
At line:1 char:13
+ $EmailField. <<<< value = "email@email.com"
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Also from the previous site I tried using the similar method as above:

[System.__ComObject].InvokeMember("value",[System.Reflection.BindingFlags]::SetProperty,$null,$EmailField,"email@email.com")


But that caused another error:

Exception calling "InvokeMember" with "5" argument(s): "Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNO
WNNAME))"
At line:1 char:34
+ [System.__ComObject].InvokeMember <<<< ("value",[System.Reflection.BindingFlags]::SetProperty,$null,$EmailField,"emai
l@email.com")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I found another link that mentioned a missing microsoft.mshtml.dll and related it to this problem with IE without Office installed, which I can't find now, but copying that file and loading it didn't make any difference in the behavior.

I can't believe I'm the only one having this problem...anyone have an idea how I can access the IE Com object on newer versions? 


I hope this post has helped!


Stopping Module on error without breaking calling script

$
0
0

Hi

What is the "best practice" to stop your PowerShell module on error but still respect the calling script $ErrorActionPreference?

For example:

Module "Test-Error.psm1":

function Test-Error
{
    [CmdletBinding()]
    param
    (
    )
    $ErrorActionPreference = 'Stop'
    do
    {
        'Start'

        #Write-Error 'Error Message' #-ErrorAction Stop
        Start-Process -FilePath nofile.exe

        #Return
        'DO NOT RAN THIS ON ERROR (End Module internal loop)'
    } while (1 -eq 1)
   'DO NOT RAN THIS ON ERROR (End Module external loop)' 
}

User script "Run.ps1":

$ErrorActionPreference = 'Inquire'
Test-Error
'RUN THIS (Not part of the module)'

This will stop the module execution on error as needed, but also stop the "user script" Run.ps1 overriding his ErrorActionPreference  so 'RUN THIS (Not part of the module)' will not run which is not desirable.

Can I use "$ErrorActionPreference = 'Stop'" or "-ErrorAction Stop" inside the module without braking the user script? separating the user script and the module "Scope" in some way maybe?
Or do I have to use "try...catch" and "Return" combination instead?

Thank you


Overwriting Fonts

$
0
0

Hi, I can successfully install fonts with PS, but it prompts me to overwrite each individual font that already exists. We have to overwrite quite a few and I am trying to incorporate this in some sort of script so having to answer about 100 dialog boxes just really doesn't work out.

I can not seem to find any way around this and surely there has to be some solution. 

This is a sample block of code I have been messing around with.

$FONTS = 0x14
$Path="c:\fonts"
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace($FONTS)
New-Item $Path -type directory
Copy-Item "path\*" $Path
Copy-Item "path\*" $Path
Copy-Item "path\*" $Path
Copy-Item "path\*" $Path
$Fontdir = dir $Path
foreach($File in $Fontdir) {
  $objFolder.CopyHere($File.fullname)
}
remove-item $Path -recurse
write-host "Installing Fonts Complete"; sleep -m 10000
Any help is greatly appreciated.

Use PS to start and stop a process depending upon the starting and stopping of another process

$
0
0

I was trying to use Task Scheduler to start Skype for Business after Outlook had started (already using it to start Outlook), and to kill SfB after Outlook was terminated. Apparently, that's beyond TS's capabilities; it was suggested I look here for help on scripting this operation. The PS scripts to start and stop Skype were simple enough; but finding how to trigger them is a galactic hemorrhoid. I would appreciate any assistance on automating this process — perhaps more accurately, these processes.

Many thanks.

Apologies for the small type. It happened when I moved the parenthetic gloss; there seems to be no way to correct that.

The application was unable to start (0xc0000142)

$
0
0

Hello,

I have bought last week a new Surface Book 2. But at this moment Powershell is unable to start.
By start Powershell there is a error: the application was unable to start (0xc0000142) 

At this moment i have tried the following things:
- SFC /scannow
- dism /online /cleanup-image /restorehealth.

But nothing will help.

Someone can help me?

Thanks in advance!

How to combine 2 objects into one

$
0
0

Hi,

I want to create report of volumes which lies on disks + with Bus Number and Target ID number of disk.

Example output should be:

PartSizeGB      : 125
PartName        : C:
PartFreeSpaceGB : 50
DiskSCSIBus      : 0
DiskModel        : ABC
DiskName         : \\.\PHYSICALDRIVE0
DiskSCSITargetId : 0

PartSizeGB      : 30
PartName        : D:
PartFreeSpaceGB : 10
DiskSCSIBus      : 0
DiskModel        : EFG
DiskName         : \\.\PHYSICALDRIVE0
DiskSCSITargetId : 1

PartSizeGB      : 500
PartName        : E:
PartFreeSpaceGB : 330
DiskSCSIBus      : 1
DiskModel        : XYZ
DiskName         : \\.\PHYSICALDRIVE1
DiskSCSITargetId : 0
I have script like this:
$DiskListOutput = @()
$PartListOutput = @()
Get-WmiObject -Class Win32_DiskDrive | ForEach-Object {

    $DiskListObj = New-Object PSObject -Property @{
        DiskName = $_.Name
        DiskModel = $_.Model
        DiskSCSIBus = $_.SCSIBus
        DiskSCSITargetId = $_.SCSITargetId
    }#end New-Object

    $DiskListOutput += $DiskListObj

    $query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" `+ $_.DeviceID + "'} WHERE ResultClass=Win32_DiskPartition"
    Get-WmiObject -Query $query | ForEach-Object {    
        $query2 = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" `+ $_.DeviceID + "'} WHERE ResultClass=Win32_LogicalDisk"
        Get-WmiObject -Query $query2 | ForEach-Object {
            $PartListObj = New-Object PSObject -Property @{
                PartName = $_.Name
                PartSizeGB = ([Math]::Round($_.Size /1GB,2))
                PartFreeSpaceGB = ([Math]::Round($_.FreeSpace /1GB,2))
            }#end New-Object
            $PartListOutput += $PartListObj
        }#end ForEach-Object
    }#end ForEach-Object
}#end ForEach-Object

So in the end I have 2 objects $DiskListOutput,$PartListOutput and I want to pair them somehow into 1 object. Could you please help? I was thinking to insert if some counter which will be identified as ID can be used as unique identifier of each objects line and join them as 3rd object.

Thank you for any help.

The original script is from here: https://itknowledgeexchange.techtarget.com/powershell/mapping-physical-drives-to-logical-drives-part-3/



Storing new user in a variable

$
0
0

I am trying to create a new user and then store it in a variable. Anyone have an idea how I would accomplish this? This is what I have so far but it's just returning null

$user = New-ADUser -Name "EMBTest Account" -GivenName EMBTest -Surname Account -SamAccountName EAccount -AccountPassword $password | Get-ADUser

Need help with a powershell script removing files in the Downloads folder

$
0
0

Hello,

I know VERY little about powershell but know enough to sort of get by. This problem is actually for work. I was tasked to find a way to remove files from the Downloads folder and delete everything greater than 30 days for all users. 

This then will probably be put on the task scheduler to run weekly.

However, if there is a better to go about this, please help me with your ideas.

Thank you,




Not able to delete the contents of a specific location(The fully qualified file name must be less than 260 characters)

$
0
0

Hi team,

I'm trying to delete the content of specific cache location in my application but it's always failing.

Command : Remove-Item "E:\Program Files\SAP BusinessObjects\tomcat\work\Catalina\*" -Recurse -Force

Error : 

Remove-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less 
than 248 characters.
At line:1 char:1
+ Remove-Item "E:\Program Files\SAP BusinessObjects\tomcat\work\Catalin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (E:\Program File...alina\localhost:String) [Remove-Item], PathTooLongException
    + FullyQualifiedErrorId : RemoveItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

Kindly help me in getting the command to delete files with long paths.

Regards,

Manhoj

 

XML node InsertAfter is not working properly

$
0
0

In VS *.csproj file, I have 3 Itemgroup tags, Inside in 2nd tag I have update one more tag like below 

       <Res Include = "3" >  
            <Culture>fr</Culture>  
        </Res>

Using insertbefore method I can update above tag at ======location 1 ======
using $root.insertafter($a, $root,itemgroup.item(1))

but I want to add the tag at ======location 2 ======and getting error 
for the same I am changing above code  as $root.insertafter($a, $root,itemgroup.item(1).name)

can not convert itemgroup type string to system.xml.xmlnode

{I just want to add node at location 2 instead of location 1 }

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">  
   1. <ItemGroup>  <X= "Strings.fr.resources" >  <Culture>fr</Culture>  </X>  <XX= "Dialogs.fr.resources" >  <Culture>fr</Culture>  </XX>  </ItemGroup> 
======location 1 don't want to add node here======
    2.<ItemGroup>  
======location 2 just want to add node here======<Res Include = "1" >  <Culture>fr</Culture>  </Res>  <Res Include = "2" >  <Culture>fr</Culture>  </Res>  </ItemGroup>

   3.<ItemGroup>  <Res YY= "Strings.fr.resources" >  <Culture>fr</Culture>  </YY>  <Res YY = "Dialogs.fr.resources" >  <Culture>fr</Culture>  </YY>  </ItemGroup><projectgroup><projectdetails = "Strings.fr.resources" >  <Culture>fr</Culture>  </projectdetails>  </projectgroup></Project>  





Invoke Webpage wowth param

$
0
0

Hi everyone. I want invoke this web page

http://www.overpass-api.de/api/xapi?node[bbox= 5.97,50.66 ,6.21,50.85] in power Shell but with param

I mean i'd like to enter These number when i invoke script. Can anyone please give me tips or idea. Thanks very much.

Invoke Webpage with param

$
0
0

Hi everyone. I want invoke this web page

http://www.overpass-api.de/api/xapi?node[bbox= 5.97,50.66 ,6.21,50.85] in power Shell but with param

I mean i'd like to enter These number when i invoke script. Can anyone please give me tips or idea. Thanks very much.


Automate Server checklist items through PowerShell or any other Script

$
0
0

Hi All,

I would like need all your help for automate below server checklist items in single script, need the requested details in single output in any format.

Server model (physical /virtual)
Os type (windows 2008 Standard or ENterprise or Windows 2003 OS)
If physical server whether ILO is reachable (just ping ILo like "c:\ping servernamerib" it should ping )
For virtual servers VMware tools status
All disks free space percentage
Server IP DNS resoultion, DNS servers, DNS suffix status, NIC binding order
Server performance, CPU, Memory utilization
Server uptime
Windows patcing status
Server time & time zone
Gather last 1 week critical & warning event logs
Check VCs software installed (Veritas cluster server)
Check whether VEA software instlled (Veritas enterprise admin)

Thank you very much all your help !!!!!

Thambi

include username in output Get-AppLockerFileInformation -EventLog

$
0
0

$event = Get-AppLockerFileInformation -EventLog -LogPath "C:\windows\system32\winevt\logs\Microsoft-Windows-AppLocker%4EXE and DLL.evtx" -EventType Audited -Statistics | Select-Object -First 1

output = 

FilePath       : %OSDRIVE%\PROGRAMDATA\APP-V\*\ROOT\VFS\PROGRAMFILESX86\ADOBE\ACROBAT READER D
                 C\READER\ACRORD32.EXE
FilePublisher  : O=ADOBE SYSTEMS, S=CALIFORNIA, C=US\ADOBE ACROBAT READER DC\ACRORD32.EXE
FileHash       : SHA256 0x04FA2719D09DD9*F52B3A8E49ED89D392FED248AADD11D
PolicyDecision : Denied
Counter        : 1

Now i am using this to send an email on a event id but i can only get the output posted above, i would like to include the username that triggerd this event, so i can include this in my email. 

can anyone help me with this? 

Thanks


Change virtual network adapters name using it macaddress.

$
0
0

Hello.

I have a bunch of virtualmachines in my lab. Im learning how to cluster/manage/conect them.

I have lot of problems identifiying the network adapters that belongs to each network.

I have a cvs file where I wrote all the info regarding to the adapters. is something like:

"""Computername""","""NIC""","""MAC""",DHCP,AddressFamily,IPAddress,PrefixLength,Type,DefaultGateway,DnsServerAddresses
VM-iSCSI,VnMGNT,00:18:59:00:01:02,true,IPv4,,,Unicast,,
VM-iSCSI,VniSCSI,00:18:59:00:01:04,false,IPv4,172.16.150.10,24,Unicast,,

I where NIC is the desired name of the adapter. I was tried some mix of scripts I  but none runs properly.

The comand I,m using now and runs properly is:

    Rename-NetAdapter -Name * -NewName VnMGT | Where-Object {$_.MacAddress -match "00-18-59-00-01-02"}

This has a lot of interactions to do, sinca I have to write down the name and the MAC.

I was wondering to know if is posible to do it comparing the MAC from the adapter with the ones in the list and do the job.

I was looking on to some post related to this but the scipts are so dificult for me to understant. I spended more tham 3 days to arrive to the comand posted a few lines before.

This are some of the posts I was reading.

https://social.technet.microsoft.com/Forums/en-US/a62b8a8c-ca02-4c76-a2b0-fb3f10deb1b5/change-dynamic-ip-to-static-ip-on-remote-machines-through-powershell?forum=winserverpowershell

https://social.technet.microsoft.com/Forums/en-US/c26ca053-942e-4f31-aa4e-5e68b4d2cad0/compare-computer-macaddress-from-csv-file-to-real-computer-macaddress-and-if-match-then-set?forum=winserverpowershell


Import a scheduled Task (XML)

$
0
0

Hi

So I have been trying to import a scheduled task I had originally created through the GUI. The task was exported successfully and I also manually imported on a couple of servers to check this out without any problems.

I have about 60-70 servers in total which I would like to roll this scheduled task out to.

I have the following script:

$txtFile="C:\Scripts\ComputerNames.txt";

Invoke-Command -ComputerName (Get-Content $txtFile) -ScriptBlock {schtasks.exe /create /RU domain\Username /RP Password /TN ExportLogs /XML "\\NAS\Share\Tasks\EventViewer.xml"}

I started testing with 10 servers and the task, this rolled out to only 2 servers with the others stating remote exception, wrong username or password. I have confirmed the administrator account I am using is a part of the domain admins security group and that the domain admins is a part of the local administrator group for each server. I have also confirmed the administrator account has full control over the NAS area. The administrator account can also RDP and start a PSSession remotely on these problematic servers. WinRM was restarted on a few servers but this had no effect. 

Changing the script to run for one of the problematic servers also yields the same result, remote exception, wrong username or password. I have also ensured PSRemoting is enabled but no change.

Invoke-Command -ComputerName $Server_Name$ -ScriptBlock {schtasks.exe /create /RU domain\Username /RP Password /TN ExportLogs /XML "\\NAS\Share\Tasks\EventViewer.xml"}

The environment is a mix of Server 2016 datacenter and Windows Server 2012 R2 datacentre. All servers are reachable and on the same network.

The only way I have managed to run this for some of these problematic servers is by importing through the GUI or running the powershell script locally for the server.

Any help would be appreciated.

Regards,

Gareth 

Invoke-webrequest with other user credentials to access kerberos IIS Site

$
0
0

Hi

System:

Using Powershell 5.0 on server 2012R2

What I want:

I want to access/load (from another server) a IIS site which is using kerberos authentication through PowerShell. I want to do this because I want the IIS Server that is hosting the site to add an Event Viewer 4624 Security message that tells me if I authenticated using Kerberos or not.

What Works:

I can remotely (from another domain joined server in PowerShell) access the site from a server via:

$SiteURL= "web.contoso.com"

Invoke-WebRequest -Uri $SiteURL -SessionVariable websession -UseDefaultCredentials

Problem:

How can i run the same Invoke-WebRequest with another domain credential ($UseThisCredential)? Like so:

 Invoke-WebRequest -Uri $SiteURL -Credential $UseThisCredential -SessionVariable websession

This gives me the error:

Invoke-WebRequest : 401 UNAUTHORIZED
At line:1 char:2+  Invoke-WebRequest -Uri $SiteURL -Credential $UseThisCredential -Sess ...+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Any tips are welcome:-)

brgs

Bjørn

Backup and Restore your AD

$
0
0

Does anyone utilize powershell scripts for daily/weekly/Monthly and production changes for backups and restores?

Thank you for any of your help?

Robb!

Returning ANY property with System.DirectoryServices.DirectorySearcher & whenchanged

$
0
0

OK, so there is this old thread - https://social.technet.microsoft.com/Forums/windowsserver/en-US/15666ba3-ba83-4ceb-9af6-77194072b413/returning-employeeid-property-with-systemdirectoryservicesdirectorysearcher

which had a nice answer, but I would need to have the property returned only when using whenchanged

$todaystamp = Get-Date -UFormat %Y%m%d%H%M%S.0Z;

whenchanged>=$todaystamp

Any idea how?

Seb


for each parallel

$
0
0

hi all

i fail to understand what mistake i have committed on the script .

i get only one result on the output even when i have multiple urls on the input file

please advise

Workflow check_site {
  $URLListFile = "C:\Users\Documents\URLList.txt" 
  $URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
  foreach -parallel -throttlelimit 100 ($Uri in $URLList) {

  inlinescript {
  $time = try{
  $Result = @()
  $request = $null
# write-host "Checking Response from " $Uri -ForegroundColor Cyan
   ## Request the URI, and measure how long the response took.
  $result1 = Measure-Command { $request = Invoke-WebRequest -Uri $using:uri -UseDefaultCredential}
  $using:result1.TotalMilliseconds

#Write-Host "Connected" -ForegroundColor green
  } 
  catch
  {<# If the request generated an exception (i.e.: 500 server
   error or 404 not found), we can pull the status code from the
   Exception.Response property #>
   $request = $_.Exception.Response
   $time = -1

  #Write-Host "Sorry the site cannot be contacted " "Error code:" ([int] $request.StatusCode) "Description :" $request.StatusDescription -ForegroundColor red


   
  }  
  $result += [PSCustomObject] @{
  Time = Get-Date;
  Uri = $Using:uri;
  StatusCode = [int] $using:request.StatusCode;
  StatusDescription = $using:request.StatusDescription;
  ResponseLength = $using:request.RawContentLength;
  TimeTaken =  $Using:time; 
  }


    #Prepare email body in HTML format
if($Using:result -ne $null)
{
    $Outputreport = "<HTML><TITLE>Website Availability Report</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Website Availability Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B></TD><TD><B>StatusCode</B></TD><TD><B>StatusDescription</B></TD><TD><B>ResponseLength</B></TD><TD><B>TimeTaken</B></TD</TR>"
    Foreach($Entry in $Using:Result)
    {
        if($Entry.StatusCode -ne "200")
        {
            $Outputreport += "<TR bgcolor=red>"
        }
        else
        {
            $Outputreport += "<TR>"
        }
        $Outputreport += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD><TD align=center>$($Entry.StatusDescription)</TD><TD align=center>$($Entry.ResponseLength)</TD><TD align=center>$($Entry.timetaken)</TD></TR>"
    }
    $Outputreport += "</Table></BODY></HTML>"

}

$Outputreport|out-file 'C:\Single.htm' -Force

}
}

}
check_site

Viewing all 21975 articles
Browse latest View live


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