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

Regular expression string format

$
0
0

Hi guys,

I am trying to read in text file and regular expression using windows powershell script. Here is my sample script as below:

$reg = "#########"
Get-Content .\aa.txt |Select-String -Pattern  $reg -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Value }

The file name is aa.txt:

12.36 -65.32 "Alice Smith" "" "" -55
36.85 -24.39 "Bob Smith" "" "" -74

In display output as above code:
12.36
-65.32
Alice Smith


-55
36.85
-24.39
Bob Smith


-74

But i want to display output like this:
12.36,-65.32,Alice Smith,,,-55,
36.85,-24.39,Bob Smith,,,-74,

I figured ....| ForEach-Object {($_ -replace "\s+",",")} and not working.

Any Idea?
Thanks


Invoke-command causes "Not enough quota is available to process this command"

$
0
0

When executing commands interactively everything works as it should but executing the same commands via a scriptblock using invoke-command returns the Failed to execute: Not enough quota is available to process this command

my particular case is using regsvr32.exe to register some dll's and ocx files.  I can run that single command in an interactive remote session one by one and it works.  Bur running it on a directory with recurse to register all the DLL's gives me that error.

something like gci C:\somedir -recurse | where-object {$_extension -eq ".dll"} | foreach (regsvr32.exe /s $_.Fullname}  fails with the not enough quota error.  So is there some remote buffer I am filling up? that I could clear out?

If i did a get-childitem and found all the DLL's and registered them one by one it works just fine.  When in the loop it will register 3-5 then error then start over registering again for 3-5 then error again and so on.

After it is finished it leaves a regsvr32.exe process running for each one that failed.

When run locally in the loop - not remoted in - then it works on all the files without any problems so it has to do with the pssession but I'm at a loss right now.

Any help is appreciated.

Get-ADComputer to query 3 domains to find the computer account

$
0
0

I am working on a script that will query three domains and tells me in which domain the server resides. I have the computers that I want to check in a CSV file and imported the information from the CSV file into a variable. Now I am testing the next step with just one pc against one domain to see if my syntax is correct. I have done a lot of reading but I just cannot find a script that does what I want. I think I have to use the startswith command but powershell doesn't like that, it tells me 

Method invocation failed because [Selected.Microsoft.ActiveDirectory.Management.ADComputer] doesn't contain a method nam
ed 'startswith'.

what method do I have to use to be able to get the canonical name returned? I actually only need the domain netbios name... I have the feeling that this isn't at all that complicated but somehow I am unable to make it work. Any help is appreciated. 

PowerShell - check AD for existing SAM account names

$
0
0

From this site and a great piece of code:

http://the-roberts-family.net/Powershell/command-line-script-to-check-a-list-of-user-account-names-in-active-directory.htm

I would like to modify this section so it returns when the name is found.  Right now it tells me if it is not found or if there is a duplicate entry in the file.  Basically I want to return data for every line in the file.

CODE:

#=============================================================================
# The basic 'ca' operation - if neither verbose of csv are specified.
# Walks through the list of usernames in the input file and reports if they
# either do not exist or are a duplicate.
#=============================================================================
function basicAccountCheck
  {
  $i = 1
  $AllOK = $True
  Get-Content $inputFile |
    foreach {
      # Strip any leading or trailing spaces
      $trimmed = $_.Trim()
      # Check for duplicates
      If ( $script:unl -contains $trimmed  )
        {"$_ is a duplicate on line $i"
        $AllOK = $False
        }
      else
        {
        $script:unl += $trimmed
        if ( ( mapUsernameToObject $trimmed ) -eq $null )
          {"$_ does not exist on line $i"
          $AllOK = $False
          } # if
        } # else
      $i++
    } # for each
    If ( $AllOK ) { "All user names exist.  No duplicates." }
  }
My reasoning for this is I want to have a list of SAM account names that I can check for duplicates in a domain before performing a AD migration using ADMT.

The ultimate would be to have it return "Duplicate - EXISTING_DN"

XCOM Transmition - Monitor transmition

$
0
0

Hey guys! I been trying to create a script file to monitor a directory that recieve incoming transmitions from a XCOM server. I found a FW (Filewatcher) code in internet and started from that. The thing is that i want the script to look for the creation of files and after a file a created i want to read the xcom.log until the transmition end. Every time that a transmition end there are two lines that say something like 

2015/04/06 12:38:10 TID=000062
    XCOMN0011I Transfer ended; 7913 records (561811 bytes) transmitted in 10 seconds (56181 bytes/second)

The "Transfer ended" is constant in every transmition

The script that i've created is:

$folder = 'D:\PowerShell\Files-XCOM' # Enter the root path you want to monitor.
$filter = '*.IN'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Here, all three events are registerd.  You need only subscribe to events that you need:

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = Get-Date -Format G
$VarWhile = 1
Write-Host "$timeStamp - Comienza transmision XCOM" -fore green
Out-File -FilePath D:\PowerShell\Files-XCOM\FileWatcher.log -Append -InputObject "$timeStamp - Comienza transmision XCOM"
}
While ( $VarWhile -eq 1 )
{
    $StringLog = Get-Content D:\PowerShell\Files-XCOM\xcom.log | Select-Object -Last 2
    if ( $StringLog -like '*Transfer ended*' )
    {
        $timeStamp = Get-Date -Format G
        Write-Host "$timeStamp - Transmision XCOM finalizada" -fore green
        Out-File -FilePath D:\PowerShell\Files-XCOM\FileWatcher.log -Append -InputObject "$timeStamp - Transmision XCOM finalizada"
        $VarWhile = 0
    }
}
# To stop the monitoring, run the following commands:
# Unregister-Event FileCreated 

The script detect when a file is created but i cant get to make it "enter" the while statement to read the log file

I cant find the error after several tries, any idea?

Region specific date formats - Incorrect InstalledOn date from Get-Hotfix

$
0
0

I first noticed when trying to look in powershell (v4) at what updates were applied after a given date by using:

Get-HotFix | where { $_.installedon -gt "12/05/2015"}

This returned no results, I expanded it to 12/05/2013, from that I received about 30 or so lines. Which to me was obviously wrong.

Running "Get-Hotfix" returns a LOT of lined but the vast majority have no ‘InstalledOn’ value.

Looking at the results and comparing them to the GUI I can see that where a date in en-GB format (dd/mm/yyyy) has a value for dd greater than 12 there is no value for ‘installedon’. I looked at other values where there was a date and if the date said it was installed on 01/12/2014 in powershell then it showed in the GUI that it was installed 12/01/2014. From that I believe that powershell is getting the date format confused with en-US (mm/dd/yyyy).

When I looked at the region settings on my PC they are all correct and show en-GB. I’ve looked at other PCs in our domain using Enter-PSSession and the same is true there too.

From the above, I know that the value for date is available as it displays OK in the GUI, but it won’t display in powershell.

Can anyone help me find out where is powershell getting confused with date formats? I’m all out of places to look right now.

-    I’m not sure if this helps but when I looked in WSUS computer status reports the language shows as en-US – I’m not sure where this is picked up from so I thought I’d include it.

Question about Large integers and the range operator in Powershell

$
0
0

I'm working on a script to create phone number blocks out of number ranges in Lync, and I have a requirement to use full e.164 numbers which can be up to 15 digits which are proving to be a bit of a problem.  When I pull out the start and end numbers for a given range, I get something like:

NumberRangeStart             : tel:+19995551200
NumberRangeEnd               : tel:+19995551299

I go to strip off the leading text and Powershell turns the number into an Int64 as expected:

$RangeStartInt = $Range.NumberRangeStart.TrimStart("tel:+")
$RangeEndInt = $Range.NumberRangeEnd.TrimStart("tel:+")

So my variables are now 19995551200 and 19995551299.  When I go to create the array using the range operator, I get:

PS C:\WINDOWS\system32> $RangeStartInt..$RangeEndInt
Cannot convert value "19995551200" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
At line:1 char:1
+ $RangeStartInt..$RangeEndInt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastIConvertible

My question is this, does the range operator only work on Int32 objects?  Is there an alternative that might work on Int64 objects or should I just use something like an i++ to create the array manually?  Any thoughts are appreciated as it's very strange...

Automate connecting to computer through RDP

$
0
0

So at my work occasionally we need to remote into a large numbers of machines. I've read that it is possible to automate this. I looked here: http://www.poshpete.com/powershell/passing-username-and-passwords-to-remote-desktop-rdp-automatically and I tried to use this script: https://gallery.technet.microsoft.com/scriptcenter/Connect-Mstsc-Open-RDP-2064b10b with no luck. I have tried using PSCREDENTIAL and breaking out the user name and password from that. I have also tired using plain text with both examples. However in all of these cases I'm am still prompted with the Windows Security Popup window to enter my credentials. Is there something I'm doing wrong? Thanks for any help!!

Update: Here's what I'm messing with. I've tried removing TERMSRV with no luck as well.

Function RDPSession {
    param(
        [parameter(Mandatory=$true)]
		[string]$Computer,
        [parameter(Mandatory=$true)]
        [PSCredential]$Credential
    )

    $User = $Credential.UserName
    $Password = $Credential.GetNetworkCredential().Password

    cmdkey /generic:TERMSRV/$Computer /user:$User /pass:$Password
    mstsc /v:$Computer

}

$cred = Get-Credential

RDPSession -Computer CEIT2551202x002 -Credential $cred


Check stopped IBM MQ Queue Managers | Powershell Script

$
0
0

Hi All,

I want to write a powershell script which can display me list of Queue Managers which are in stopped state. Please note that we are using IBM MQ's.

I know there is a command dspmq <Queue Manager Name> to display status of a specific queue manager, but i want to list all the queue manager status which are in Stopped (Ended) state and then start them on the basis of user input. Can anyone tell me the script for the same?


A "tail -f" equivalent command in Powershell to show real time logging

$
0
0

Hello,

Using the powershell command:
Get-Content "Filename" -Wait -Tail 10
showing Real-Time contents of a file in powershell doesn't work.

As example i would like to show Real-Time contents of a systemout.log file in a IBM Websphere Environment.

Using the above command, the shell remain in "listening mode" but nothing happens even if the Systemout.log file changes.

In a unix environment it is enough to type "tail -f filename" and everything work correctly.

Is it possible to use a "tail -f" equivalent command in Powershell to show real time logging?

Thank You in advance.

Fausto.


mozilla fox fire

$
0
0
mozilla fox fire keeps coming up incompatible so I searched for answer and got instruction to type "cmd.exe." into Search then right-click 0n command prompt to select  Run as Administrator then type "netsh winsock reset into command prompt, press enter then restart pc . I am not sure which "Search" I am suppose to use can I get assistance with this problem?

Select specific data from TextFile

$
0
0

I have a text file with following layout  (IMAGE ABOVE).  i want to extract specific date from each row into excel.

Item-#         wharehouse         Description-1              Description-2      Lst-sls-dat        Qty-on-hand   Stocking-unit

25300001   Cen  Main Store     STUD, REAR WHEEL   54494R1             12/23/14         30                     EA 

How can i get the data above in this Format ?

Your help would be greatly appreciated newbie !!!

A Shell scripting solution in Windows to test ping and telnet to multi_site Help

$
0
0

I allow myself to write to you following a several day lock to solve the problem of the code I'm linux bash, I'm in no shell.

The principle of this code is to do:

  • Test: ping GOOGLE.FR and test.FR telnet test 10050 telnet localhost 20150

  • And display the hostname of windows machine and its SSID.

Desired result for the ping and telnet: results should display if the ping test is good then display "success" if not display "failed", same principle for telnet.

Once my code runs must send me the log files in a specific way, and send me a result report by email if possible.

I ask for a feedback please. Thank you for your return.

# récuperer hostname $env:computername# test connectivité google et code42$ServerName = "www.google.fr","www.code42.fr"##### Script Starts Here ###### foreach ($Server in $ServerName) {        if (test-Connection $Server -Count 2 -Quiet ) {                     write-Host "$Server succes " -ForegroundColor Green                            } else                    


                    { Write-Warning "$Server failed"
            
                    }    
        
}


Send-MailMessage Help

$
0
0

So I am trying to send a report generated by a PS script. I have this:

send-mailmessage -From User@mail.com -Subject "Test Email" -To User2@mail.com -smtpserver ip.address -Attachments C:\Scripts\*_RDP_Report.csv

I get this when running from PS:

Export-Csv : Cannot find drive. A drive with the name '/' does not exist.
At C:\Scripts\RDPConnectionParser.ps1:55 char:38+ $FilteredOutput | Sort TimeCreated | Export-Csv $env:C:\Scripts\$Date`_RDP_Repo ...+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (/:String) [Export-Csv], DriveNotFoundException+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.ExportCsvCommand

send-mailmessage : Cannot perform operation because the wildcard path C:\Scripts\*_RDP_Report.csv did not resolve to a file.
At C:\Scripts\RDPConnectionParser.ps1:57 char:1
+ send-mailmessage -From RDSAuditReport@teknerds.net -Subject "Test Email" -To car ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OpenError: (C:\Scripts\*_RDP_Report.csv:String) [Send-MailMessage], FileNotFoundException+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.SendMailMessage

The PS script and report are located at C:\Scripts. Here is the export part of the PS script that generates the report:

$Date = (Get-Date -Format s) -replace ":", "."
$FilteredOutput | Sort TimeCreated | Export-Csv "C:\Scripts\$Date`_RDP_Report.csv" -NoTypeInformation

It looks to me like it does not like the "C:\" part. How do i tell PS where to find the report located at C:\Scripts?

Microsoft.Update.AutoUpdate NotificationLevel

$
0
0

Im working with PS Studio.

I wrote this script.

It isnt working aswell. As you see its bottom click. But when I open PS command prompt and hit this strings line by line, it is!

Can someone tell me why?

$checkud_Click = {


    $AUSettigns = (New-Object -com "Microsoft.Update.AutoUpdate").Settings
$AUSettigns.NotificationLevel = 1
$AUSettigns.Save

}

 

Avoid the prompt for - the data you are pasting is not the same size- using PowerShell

$
0
0
How to use powershell to avoid the prompt for "the data you are pasting isnot the same size as your selection ...." Can I avoid this using PowerShell API? I want to say "Yes" for this prompt through powershell. I am using $myworksheet.Paste($range) but the prompt for paste and save needs to be avoided.

How do I get the number of physical and virtual processors on a virtual server

$
0
0

I have a script from Jesse Hamrick that gathers information about servers that I am altering to suit my needs. one of the things I need to gather is the number of physical and virtual processes on a virtual server. I've looked around and really don't see exactly what I'm looking for. Can someone here point me in the right direction, please? I am very new to PowerShell.


Thank you!


Start-Job works from Powershell but not from CMD

$
0
0

Hi guys,

I'm trying to get the Powershell command Start-Job working from the classic command line because in my special case I need to execute this command from the classic CMD.

When I execute the follwoing command from the Powershell everything works fine ("run" is a mandatory argument for the bat script) and the scripts starts:

Start-Job -ScriptBlock {path_to_bat.bat run} 

But when I try to execute this from CMD through:

powershell -command Start-Job -ScriptBlock {path_to_bat.bat run}

I also receive the output 

Id     Name            PSJobTypeName   State         HasMoreData     Location  
--     ----            -------------   -----         -----------     --------  
1      Job1            BackgroundJob   Running       True            localhost 

but the script didn't start.

I have executed varios commands through "powershell -command ..." and everthing worked fine but the Start-Job always fails.

Thanks in advance for help!

Cheers,

Daniel 

Hosted Powershell showing console window in Windows Application for external program calls

$
0
0

I'm writing an embedded powershell host in C# (windows application), and if there is an external program called in the pipeline the console window flashes as it's executed. Ping and netstat are examples of this as shown in the following code snippet

using (PowerShellPowerShellInstance=PowerShell.Create()){PowerShellInstance.AddScript("Get-Content test.txt; ls; ping www.google.com");PowerShellInstance.Invoke();# ...more code here to print output etc}

Once the ping command (or really the first external program called) is reached in the pipeline a console window will popup execute the command and return results. This only seems to happen once, and then subsequent external calls do not show the console window (e.g. ping is called again). I would like to do this without the console window showing. I've searched and found examples of how to deal with this by starting a process for external commands and redirecting output.

I can do that of course, but then how would I test if a command in the pipeline is a call to an external program?

I would really like to be able to handle this generically if possible; meaning that I don't want to test for specific programs (e.g. ping, netstat, net) if I don't have to. The native powershell.exe does this so it's somehow possible.

Tested on Windows 8.1 and 7

ProductKey : BBBBB-BBBBB-BBBBB-BBBBB-BBBBB

$
0
0

Trying to recover Win 8.1 Product Key 64 bit.

1. Made TEXT FILE RecoverKey.ps1on desktop

function Get-WindowsKey {
    ## function to retrieve the Windows Product Key from any PC
        param ($targets = ".")
    $hklm = 2147483650
    $regPath = "Software\Microsoft\Windows NT\CurrentVersion"
    $regValue = "DigitalProductId64"
    Foreach ($target in $targets) {
        $productKey = $null
        $win32os = $null
        $wmi = [WMIClass]"\\$target\root\default:stdRegProv"
        $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue)
        $binArray = ($data.uValue)[52..66]
        $charsArray = "B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9"
        ## decrypt base24 encoded binary data
        For ($i = 24; $i -ge 0; $i--) {
            $k = 0
            For ($j = 14; $j -ge 0; $j--) {
                $k = $k * 256 -bxor $binArray[$j]
                $binArray[$j] = [math]::truncate($k / 24)
                $k = $k % 24
            }
            $productKey = $charsArray[$k] + $productKey
            If (($i % 5 -eq 0) -and ($i -ne 0)) {
                $productKey = "-" + $productKey
            }
        }
        $win32os = Get-WmiObject Win32_OperatingSystem -computer $target
        $obj = New-Object Object
        $obj | Add-Member Noteproperty Computer -value $target
        $obj | Add-Member Noteproperty Caption -value $win32os.Caption
        $obj | Add-Member Noteproperty CSDVersion -value $win32os.CSDVersion
        $obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture
        $obj | Add-Member Noteproperty BuildNumber -value $win32os.BuildNumber
        $obj | Add-Member Noteproperty RegisteredTo -value $win32os.RegisteredUser
        $obj | Add-Member Noteproperty ProductID -value $win32os.SerialNumber
        $obj | Add-Member Noteproperty ProductKey -value $productkey
        $obj
    }
}

2. Ran PowerShell as admin
3. Set-ExecutionPolicy RemoteSigned Y
4. Import-Module C:\Users\Francois\Desktop\RecoverKey.ps1; Get-WindowsKey

Returns Product ID properly, but not key:
ProductKey   : BBBBB-BBBBB-BBBBB-BBBBB-BBBBB

Viewing all 21975 articles
Browse latest View live


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