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

PowerShell via Task Scheduler

$
0
0

I have a PowerShell script that is scheduled to trigger every 30 minutes. I have noticed that sometimes it works and sometimes it does not work.

 

When it does not work I see two event message one in the application log that is 1530 for User Profile Service:

 

Windows detected your registry file is still in use by other applications or services. The file will be unloaded now. The applications or services that hold your registry file may not function properly afterwards. No user action is required. 

 

 DETAIL -

 3 user registry handles leaked from \Registry\User\S-1-5-21-2705007612-1783374947-2115659154-1391_Classes:

Process 3680 (\Device\HarddiskVolume4\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) has opened key \REGISTRY\USER\S-1-5-21-2705007612-1783374947-2115659154-1391_CLASSES

Process 3680 (\Device\HarddiskVolume4\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) has opened key \REGISTRY\USER\S-1-5-21-2705007612-1783374947-2115659154-1391_CLASSES

Process 3680 (\Device\HarddiskVolume4\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) has opened key \REGISTRY\USER\S-1-5-21-2705007612-1783374947-2115659154-1391_CLASSES

 

And Error 103 in the Windows PowerShell log:

 

Settings: Could not read key from registry (Exception from HRESULT: 0x80040150 (REGDB_E_READREGDB))

 

Details:

               ExceptionClass=COMException

               ErrorCategory=

               ErrorId=

               ErrorMessage=Could not read key from registry (Exception from HRESULT: 0x80040150 (REGDB_E_READREGDB))

 

               Severity=Error

 

               SequenceNumber=

 

               HostName=ConsoleHost

               HostVersion=4.0

               HostId=ca5012f3-3817-4550-a22f-64e63a5d653f

               HostApplication=

               EngineVersion=4.0

               RunspaceId=cae95f53-8727-433e-93fa-8c770e4af4b5

               PipelineId=

               CommandName=

               CommandType=

               ScriptName=

               CommandPath=

               CommandLine=

 

AdditionalInfo:

               Name=;Value=

               Name=;Value=

 

Out of 20 possible runs this set of events occurs 8 times in a 10 hour window. any suggestions would be great.

Thanks,


Multiple perfmon counters or multiple cmdlets at the same time

$
0
0

is it possible to run multiple cmdlets at the same time or is it possible to use get-counter to get results from multiple counters at the same time

For example :

Get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 1

Get-counter -Counter "\Process(*)\% Processor Time" -SampleInterval 1 -MaxSamples 1

Can i run these 2 commands in parallel or is there anything like i can make the counters \Processor(_Total)\% Processor Time and \Process(*)\% Processor Time to return values at the same time?

Compare dates

$
0
0

Hi

I'm trying to ascertain how long ago (hours/days) a change was made to specific attributes in Active Directory. I'm doing this by comparing the date on the individual attribute metadata with the current time.

However, I can't find a way to compare the two dates.  Here's the code I'm using to find/compare the dates- can anyone help?

$meta = $dc.GetReplicationMetadata($objectDN)

$today = get-date | select-object date | ft -HideTableHeaders $llts = $meta.lastlogontimestamp | select-object LastOriginatingChangeTime | Format-Table -HideTableHeaders if ($llts -gt $today) {write-host Bingo}

When running this code, I get

Cannot compare "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" because it is not IComparable.
At line:1 char:5
+ if ($llts -gt $today) {write-host Bingo}
+     ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NotIcomparable

Code Doesn't Work With PowerShell 5 Furthermore

$
0
0

Hello community,

I am using SAP GUI Scripting with PowerShell. Last week I update to PowerShell 5.0.10586.117. But now the code, which runs with PowerShell 4 trouble-free, throws an error. I checked the same code with Visual Basic Script an it works without any problems. Here the VBScript code inside PowerShell:

#-Begin-----------------------------------------------------------------

  $VB = New-Object -COMObject MSScriptControl.ScriptControl

$Cmd = @"
Set SapGuiAuto = GetObject(`"SAPGUI`")`n
Set application = SapGuiAuto.GetScriptingEngine`n
Set connection = application.Children(0)`n
Set session = connection.Children(0)`n
session.findById(`"wnd[0]/tbar[0]/okcd`").text = `"/nse16`"`n
session.findById(`"wnd[0]/tbar[0]/btn[0]`").press`n"@

  $VB.Language = "VBScript"
  $VB.AllowUI = $TRUE
  $VB.ExecuteStatement($Cmd)

#-End-------------------------------------------------------------------

Here now the equivalent PowerShell code:

#-Begin-----------------------------------------------------------------

  #-Load assembly-------------------------------------------------------
    [Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") > $Null

  #-Get-Property--------------------------------------------------------
    function Get-Property {
      param([__ComObject] $object, [String] $propertyName)
      $object.GetType().InvokeMember($propertyName,
        "GetProperty", $NULL, $object, $NULL)
    }

  #-Set-Property--------------------------------------------------------
    function Set-Property {
      param([__ComObject] $object, [String] $propertyName,
        $propertyValue)
      [Void] $object.GetType().InvokeMember($propertyName,
        "SetProperty", $NULL, $object, $propertyValue)
    }

  #-Invoke-Method-------------------------------------------------------
    function Invoke-Method {
      param([__ComObject] $object, [String] $methodName,
        $methodParameters)

      #$obj = $object.GetType()
      #throws the error
      #Fehler beim Laden der Typbibliothek/DLL.
      #(Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))

      $output = $object.GetType().InvokeMember($methodName,
        "InvokeMethod", $NULL, $object, $methodParameters)
      if ( $output ) { $output }
    }

  #-Main----------------------------------------------------------------
    $SapGuiAuto = [Microsoft.VisualBasic.Interaction]::GetObject("SAPGUI")
    $application = Invoke-Method $SapGuiAuto "GetScriptingEngine"
    $connection = Get-Property $application "Children" @(0)
    $session = Get-Property $connection "Children" @(0)

    $ID = Invoke-Method $session "findById" @("wnd[0]/tbar[0]/okcd")
    Set-Property $ID "Text" @("/nse16")
    $ID = Invoke-Method $session "findById" @("wnd[0]/tbar[0]/btn[0]")
    Invoke-Method $ID "press"

#-End-------------------------------------------------------------------

The code line $obj = $object.GetType() throws the error: Error loading type library / DLL.

My problem is, I don't have the slightest idea which type library or DLL is meant. Is there any way to detect the name of the missing type library or DLL?

Thanks for tips and hints.

Cheers
Stefan

Auto Run PowerShell script from WinPE

$
0
0

I'm in the process of creating a PS script that backs up files from locations I've specified.  It currently works while in Windows, but I am now trying to get it to work upon booting from a WinPE USB drive.

I've gathered that my options to accomplish this are startnet.cmd and winpeshl.ini.  I have also already added the necessary packages for PowerShell functionality.

I have briefly played around with the startnet.cmd way, but am not able to get my script to automatically run after starting PowerShell.  I figured startnet.cmd is not the way to go anyway as it seems it is meant for Windows command-line scripting anyway.  I  have been researching how to use the winpeshl file, however I'm not really sure where to start at this point.  Where do I place the .ps1 file?  Do I need to place .ps1 inside an .exe in order for it to be an 'app', etc.?

Pages I'm already familiar with:

WinPE: Adding PowerShell support to Windows PE

https://technet.microsoft.com/en-us/library/dn605289.aspx

Winpeshl.ini Reference: Launching an app when WinPE starts
https://msdn.microsoft.com/en-us/library/windows/hardware/dn938379%28v=vs.85%29.aspx

Include a Custom Script in a Windows PE Image
https://technet.microsoft.com/en-us/library/cc766521%28v=ws.10%29.aspx


Changing width of [System.Windows.Forms.MessageBox]

$
0
0

Hi, i have a script that displays output to a [System.Windows.Forms.MessageBox]. The problem i have is that the messagebox is not wide enough to display the information.  Is there a way of modifying the width of the message box ?

thanks

Does anyone know when to you use '+' or '.' when accessing enum values (or other class members perhaps)?

$
0
0

Example:

To get the documents and settings folder from powershell, you do something like:

[System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::MyDocuments)

SpecialFolder is a .NET enumerator, but it can't be accessed by [System.Environment.SpecialFolder]::MyDocuments syntax...

On other hand - a member of the SearchOption (System.IO namespace) enumerator is accessed by:

[System.IO.SearchOption]::AllDirectories

Does anyone know what is the difference?

Scheduled PowerShell script cannot call external program on Windows Server 2012 R2

$
0
0

Hi guys, 

we've recently migrated our solution/scripts from Windows Server 2008 R2 (64-bit) to Windows Server 2012 R2 (64-bit). One of the PowerShell scripts, scheduled to run in TaskScheduler, doesn't work as expected. Actually only one command, calling external program to decrypt pgp file, doesn't work. If the user, under which the script is scheduled, is logged in, even disconnected, the script works. It works also interactively. But it doesn't work as scheduled job if that specific user is not logged in. I've changed default PowerShell policy to ByPass, added user (domain user) to local admin group, "Log on as a batch job" group in local security policy, but it didn't help. I've also changed the pgp decrypting software (GPG4Win 2.3 to Symantec PGP command line tool), played with couple styles how to call external program from PowerShell, but the main issue remains: It works if the user is logged in (even disconnected), but it doesn't work if the user is not logged in. Did I miss any security setting? Do you have any idea/experience why this is happening?

Thanks.

Dragan


My First PowerShell Function

$
0
0

I am attempting to write my first powershell function. Here is the sample and it is not executing as expected. My problem is when you run it and it returns a positive result is should run the second path gathering WMI BIOS info and it is not, but why?

The server.txt is a simple text file with computer/server names

(I am running this on Windows 10 , PS version 5.0.1.586.63)

Param([string]$computer = $env:computername) Function Get-AllowedComputer([string]$computer){ $servers = Get-Content -path c:\temp\servers.txt $servers -contains $computer } #end Get-AllowedComputer function

# *** Entry point to Script *** if(Get-AllowedComputer -computer $computer){ GWMI Win32_Bios -Computer $computer} Else{"$computer is not an allowed computer"}

 



Difference between Remove-Item in Powershell 3.0 and 4.0

$
0
0

Hi! Just a simple question

Seems that there is a difference between PS version 3 and 4 running this command, because in PS 3 it leaves the content in the GetFoldersizePortable (which is a folder) and in PS 4 it doesnt

Remove-Item -Path 'C:\temp\*' -Recurse -Exclude WindirStat.exe, GetFoldersizePortable

My question is why, and how to work around this


Remote-Shutdown fails on Windows 10

$
0
0

Hi!

I have a number of computers running Windows 8.1 and Windows 10 that I need to reboot remotely. All the computers are used for development purposes and no one is connected to an AD. I use the Restart-Computer command from Powershell. It works fine with the Windows 8.1 machines but not the Window 10 machines. There, I get an access denied error. 

I have spent most of my day trying to find a solution, reading tons of forum entries and tips but nothing works.

I should add that these machines are used embedded so they are more or less clean installs.

I'm grateful for some expertise help!

/Peter

ForEach loops to coordinate data from two different arrays?

$
0
0

Greetings all!

I have a PowerShell problem for which the answer does not readily present itself. 

I have two Domains, Prod and Test.  I am running a PowerShell script from a Prod utility server.  I want to synchronize user accounts between the two domains.  Part of that synchronization is to create accounts in Test that correspond to existing accounts in Prod.

First, I have created two Arrays ($UsersProd and $UsersTest) using get-aduser in both Domains.  This grabs multiple properties for each account.

Second, I do a compare-object with $UsersProd and $UsersTest and get a list of Account names that exist in Prod but do not exist in Test.

$LoneNames = compare-object $UsersProd $UsersTest -property name | where-object {$_.SideIndicator -eq '<='}

Here is what I can't figure out how to do.  I need to go down the list of account names in $LoneNames one-by-one and create an account in Test for each one.  Using

ForEach ($Name in $LoneNames)

works well for going down the list.  But, I also need to grab the properties of that account from $UsersProd and configure the new account in Test with those same properties.  Clearly, it will have to fulfill the requirement that $Name (from $LoneNames) will have to equal $UserProd.name (from $UserProd).

I tried nested ForEach loops and tried If and Elseif statements.  No joy.

Has anyone ever had to do this before and if so, how did you do it?

Set Multi-value Lookup Field Value using Powershell

$
0
0

Hi;

I try to update a Lookup Field Value using Powershell but whitout success ? Any error but any change on the field value (Market).

My script is :

function UpdateField
{
 param([Microsoft.SharePoint.SPWeb]$web,
 [Microsoft.SharePoint.SPList]$list,  string $inputvalue )

$SPListItems = $list.Items
  if ($SPListItems -ne $null)
   {
    foreach ($item in $SPListItems)
    {

     //get the current value + ID of the field

     $lookupMarket  = [Microsoft.SharePoint.SPFieldLookupValue]$item["Market"]  
     $lookupvalueMarket = $lookupMarket.LookupValue    //old value
     $lookupvalueIDMarket = $lookupMarket.LookupID   //ID
      if ($inputvalue  -eq "OK")
      {

        //update the field with the new value : inputvalue       

        $LookupValues = new-object Microsoft.SharePoint.SPFieldLookupValue($lookupvalueIDMarket,     $inputvalue)
       $item["Market"] = $LookupValues
       $item.Update()}

}}

Regards


copy objectguid value to extensionattribute

$
0
0

Hi all,

in a very complex AD/O365 consolidation project i need to copy the objectguid value for each user to extensionattribute15

However i convert the value to bytearray or base64, the copied value in extensionattribute15 is never the same as in objectguid

Does anyone have an idea how the value needs to be converted in powershell?

Thanks.

How to browse the powershell namespaces?

$
0
0

How do I expose/browse types/methods/classes exposed in powershell modules and utility libraries.  ILSpy?

For instance:

How do I find System.Math without having to need it first and then googling it first and found someone who figured it out.


Powershell remove machine from domain

$
0
0

Hi all

I have been working on a script to remove machines from the domain. I am running into a couple of different issues.

1. The machine is not in ad and the local machine thinks it still it. It will not remove itself because it thinks it is and AD says id doesn't exist.

2. The machine does not think it is in AD but the tree says it is. For some reason, it is not trying to take control of the machines account. 

This is my line to join the domain. "Add-Computer -DomainName "domain.xyz" -Credential $cred -PassThru -OUPath $strOU"

This is my line to remove it from the domain. "remove-computer -credentials $cred"

I do check to see if it is part of the domain using this. "if((gwmi win32_computersystem).partofdomain)"

I know I am obviously missing something. I know when I test this, I get no errors. On the machines that techs have errors, I get the same errors. So I don't think it is an issue permissions.

Most of our machines are running poweshell 2, but I have been begging to PS4 to get installed and it has not happened yet. So, if there is a command in PS4, I might be able to get them to push it out to fix the issues we are having.

Thank you guy

Charles

Power Shell Set Printing Defaults

$
0
0

I need a powershell script to set the paper type in the Printing Defaults section of a printer driver, I have a number of devices that have gotten changed from unspecified to prepunched or preprinted, etc.

I would also like to know how to change the paper size, paper source, etc.  I've actually found documentation on how to set duplex mode.

I've looked into get-printerproperty and set-printerpropertybut I cannot find a property for these elements.

Thanks.

Get-Aduser Error Handling

$
0
0

Hi Guys,

I have a text file which contains email address. Now some of them are not valid users for my domain. When I am using 

Get-ADUser -Filter {EmailAddress -eq "Emailaddress"} |select SamAccountName, its giving me the result of valid address but for invalid mails, nothing comes in. Any suggestion what can be done to generate the error of invalid mail id's. 

Please note, I have used Get-Content and foreach loop, no issue with that.

Thanks in Advance. 

Office365 - Search specific mailbox - download attachments where type=zip & sender is ..

$
0
0

hi

how can I achieve searching a specific users mailbox and download any attachments with attachment:zip and from:some@domain.local..

I've been looking at this:

Get-Mailbox -Identity source@domain.local | Search-Mailbox -SearchQuery 'attachment:zip AND From:dataleverancer@hotmail.com'

but it seems to need a target mailbox.. so I added:

-targetmailbox me@domain.local -targetfolder Test -loglevel Full

which does give me "some" emails.. but what I really want is to skip the target part and just download them to a folder where another service can monitor the contents...


Kindest regards, Martin

NEW-PSDRIVE - Active Directory Persistence

$
0
0

Hi 

I'm trying to set up new PSDrives on my local machine so that I can administer remote domains without having to log on to the various serves in those domains.

I have used the following command to create the drive, it works and I have no issues.

New-PSDrive -Name remotedomain -PSProvider ActiveDirectory -Server "192.168.0.1" -Credential (Get-Credential "domain\administrator") -Root "//RootDSE/" -Scope Global 

The issue I have is that when I shut down by powershell session those newley created PSdrive are gone.  I've tried using the           -persist option but that gives me the following message:

New-PSDrive : When you use the Persist parameter, the root must be a file system location on a remote computer.

How would I get them to stay put when I close my powershell session.

Viewing all 21975 articles
Browse latest View live