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

Export all AD Sites, Subnets, and SiteLinks and then import to different system

$
0
0

Hi,

Any suggestions on how to export all AD Sites, Subnets, and SiteLinks from a Server 2008 R2 Domain and then import and define to a Server 2012 R2 Domain?  I've seen isolated export and import scripts, but not an export and import script pair which works together.  Any help here would save me lots of time from manually defining.


Thanks for your help! SdeDot


Scriptblock basics

$
0
0

I'm hoping someone can enlighten me on this...

$oldaccts = Get-ADUser -Filter { LastLogonTimeStamp -lt $daysago } -Properties * |
    Select-Object -Property Name, @{ prp = 'LastLogonTimeStamp'; val = {[DateTime]::FromFileTime($_.LastLogonTimeStamp)} } 

What is this: @{ prp = ... ; val = ...}  (is it a hashtable? scriptblock?)

Why is the conversion to DateTime in curly brackets?

How do I sort this by date ascending?

Expand-WindowsImage Error when using SplitImageFilePattern

$
0
0

I have been using batch for a very long time for some of our custom deployment jobs and i have come to the realization that I need to move on so I've started changing old code to PS but have hit a wall with this one.

I'm trying to apply a split image, with batch I would simply do:

DISM /Apply-Image /Imagefile:%Image% /Applydir:%OSVol% /SWMFile:%SWMFile% /Index:%IndexNumber%

However when I try this in PS (v4.0 in PE 6.3) using the following command:

Expand-WindowsImage -ImagePath "$USBDrive\$Image" -SplitImageFilePattern "$USBDrive\$SWMImage" -ApplyPath "$OSVol" -Index $IndexNumber

I keep getting this error:

Expand-WindowsImage : Cannot create a file when that file already exists. (Exception from HRESULT: 0x800700B7)
At line:1 char:1+ Expand-WindowsImage -ImagePath E:\$USBDrive\$Image -SplitImageFilePattern  ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Expand-WindowsImage], COMException+ FullyQualifiedErrorId : Microsoft.Dism.Commands.ExpandWindowsImageCommand

If i remove the SplitImageFilePattern parameter the image will apply fine until it needs the next segment where it will error out as expected, however I have no idea why when using an SWM it keeps saying the file already exists and cannot be created.


Powershell to get AD CS and AD RMS details

$
0
0

Hi Guys,

I need to access AD CS and AD RMS on remote server (windows 2003 - which do not have powershell or some servers have only powershell 1.0)

From server 2008 onwards, i have below cmdlets

Get-RmsCertChain
Get-RmsCertInfo
Get-RmsChildCert
Get-RmsEncryptedIL
Get-RmsRequestInfo
Get-RmsSvcAccount
Get-RmsSystemHealthReport
Get-RmsUserRequestReport


Get-CAAuthorityInformationAccess
Get-CACrlDistributionPoint
Get-CATemplate

 

But, how can i do the same for Server 2003, do i need to use any WMI in this case.

Please suggest.

The WinRM service is not listening for WS-Management requests. Event ID 10149

$
0
0

Dears,

One -domain joined- server has Windows Remote Management not working even after running the command WINRM QUICKCONFIG and Enable-PSRemoting many times successfully.. I still can't connect to this server using WMI commands.

I checked the event log and found Event ID 10149 The WinRM service is not listening for WS-Management requests.

  - Windows Firewall is turned off and network traffic is opened between my client and all servers.

  - Other servers has WMI working fine and I can manage them.

  - The server is batched with last updates.

  - OS : Windows Server 2012 R2 Datacenter

  - Server role is Hyper-V host

Please help what can we do to fix this issue..

Thanks,

A Seyam

Calculate Columns of an object

$
0
0

Any way to get how many columns an object has ?

Im nto alking about Obj.count which resturns how many items the array/object contains, but how many poperties its returning.

Thanks for any help

Regards,

Structuring Get-GPResultantSetOfPolicy

$
0
0

Hello everyone, I am very new at trying to parse XML data with PowerShell and starting to beat my head on something.

I generate a report using Get-GPResultingSetOfPolicy and would like to parse the data out into a CSV type format along the lines of :

GPO Name

Path to Setting

Setting, Value

I am able to readh in the content using:

[xml]$xmlDocument = (Get-Content "C:\data\gp.xml")

then pull content using:

$xmlDocument.Rsop.UserResults.ExtensionData.Extension.ChildNodes | ForEach-Object {$_.Name ; $_.InnerText};

However the inner text is all lumped together like so on return:

q5:RegistryRsopSetting
{8343861A-85CA-4B8B-BD0A-03DB1E3BA161}corp.contoso.com1IETourNoShowcn={8343861A-85CA-4B8B-BD0A-03DB1E3BA161},cn=policies,cn=system,DC=com,DC=contoso,DC=comOU=Computers,OU=Corp,OU=Sites,DC=corp,DC=con
toso,DC=com{BEE07A6A-EC9F-4659-B8C9-0B1937907C83}{B087BE9D-ED37-454f-AF9C-04291E351182}ContosoGPO-3{8343861A-85CA-4B8B-BD0A-03DB1E3BA161}{AA36DD3F-619D-4902-98BB-5AF2ABD1BBF0}120151026134241.699000+0
00RSOP_PolmkrRegistrySetting.polmkrHive="HKEY_CURRENT_USER",polmkrKey="Software\Microsoft\Internet Explorer\Main",polmkrDefault="0",polmkrName="IETourNoShow"{9CD4B2F4-923D-47f5-A062-E897DD1DAD50}IETo
urNoShowIETourNoShow122014-08-07 19:11:02{8071A6B0-9984-4FFC-BBE1-139191E537B7}1U00HKEY_CURRENT_USERSoftware\Microsoft\Internet Explorer\MainIETourNoShowREG_DWORD00000001U000000001HKEY_CURRENT_USERSo
ftware\Microsoft\Internet Explorer\MainIETourNoShowREG_DWORDValue00x00000000The operation completed successfully.

Ideally i would like to pull each individual innertext and relate it to the parent node.  Here's the snippet of XML I am working with.

Hope this makes sense!  Any ideas or pointers would be greatly appreciated!

<?xml version="1.0" encoding="utf-16"?><Rsop xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.microsoft.com/GroupPolicy/Rsop"><ReadTime>2015-11-09T17:55:48.5091125Z</ReadTime><DataType>LoggedData</DataType><UserResults><Version>2228228</Version><Name>DOMAIN\User</Name><Domain>corp.contoso.com</Domain><SOM>corp.contoso.com/Sites/corp/Users</SOM><Site>Corp</Site><SlowLink>false</SlowLink><ExtensionData><Extension xmlns:q5="http://www.microsoft.com/GroupPolicy/Settings/Windows/Registry" xsi:type="q5:RegistrySettings" xmlns="http://www.microsoft.com/GroupPolicy/Settings"><q5:RegistryRsopSetting><GPO xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base"><Identifier xmlns="http://www.microsoft.com/GroupPolicy/Types">{8343861A-85CA-4B8B-BD0A-03DB1E3BA161}</Identifier><Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">corp.contoso.com</Domain></GPO><Precedence xmlns="http://www.microsoft.com/GroupPolicy/Settings/Base">1</Precedence><q5:BaseInstanceXml CLASSNAME="RSOP_PolmkrRegistrySetting"><q5:PROPERTY NAME="name"><q5:VALUE>IETourNoShow</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="GPOID"><q5:VALUE>cn={8343861A-85CA-4B8B-BD0A-03DB1E3BA161},cn=policies,cn=system,DC=com,DC=contoso,DC=com</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="SOMID"><q5:VALUE>OU=Computers,OU=Corp,OU=Sites,DC=corp,DC=contoso,DC=com</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrBaseGpeGuid"><q5:VALUE>{BEE07A6A-EC9F-4659-B8C9-0B1937907C83}</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrBaseCseGuid"><q5:VALUE>{B087BE9D-ED37-454f-AF9C-04291E351182}</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrBaseGpoDisplayName"><q5:VALUE>ContosoGPO-3</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrBaseGpoGuid"><q5:VALUE>{8343861A-85CA-4B8B-BD0A-03DB1E3BA161}</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="id"><q5:VALUE>{AA36DD3F-619D-4902-98BB-5AF2ABD1BBF0}</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="precedence"><q5:VALUE>1</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="creationTime"><q5:VALUE>20151026134241.699000+000</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrBaseHash"><q5:VALUE>RSOP_PolmkrRegistrySetting.polmkrHive="HKEY_CURRENT_USER",polmkrKey="Software\Microsoft\Internet Explorer\Main",polmkrDefault="0",polmkrName="IETourNoShow"</q5:VALUE></q5:PROPERTY><q5:INSTANCE CLASSNAME="RSOP_PolmkrRegistryItem"><q5:PROPERTY NAME="polmkrClassClsid"><q5:VALUE>{9CD4B2F4-923D-47f5-A062-E897DD1DAD50}</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassName"><q5:VALUE>IETourNoShow</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassStatus"><q5:VALUE>IETourNoShow</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassImage"><q5:VALUE>12</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassChanged"><q5:VALUE>2014-08-07 19:11:02</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassUid"><q5:VALUE>{8071A6B0-9984-4FFC-BBE1-139191E537B7}</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassBypassErrors"><q5:VALUE>1</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrAction"><q5:VALUE>U</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrDisplayDecimal"><q5:VALUE>0</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrDefault"><q5:VALUE>0</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrHive"><q5:VALUE>HKEY_CURRENT_USER</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrKey"><q5:VALUE>Software\Microsoft\Internet Explorer\Main</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrName"><q5:VALUE>IETourNoShow</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrType"><q5:VALUE>REG_DWORD</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrValue"><q5:VALUE>00000001</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrActionResolved"><q5:VALUE>U</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrDefaultResolved"><q5:VALUE>0</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrValueResolved"><q5:VALUE>00000001</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrHiveResolved"><q5:VALUE>HKEY_CURRENT_USER</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrKeyResolved"><q5:VALUE>Software\Microsoft\Internet Explorer\Main</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrNameResolved"><q5:VALUE>IETourNoShow</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrTypeResolved"><q5:VALUE>REG_DWORD</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrAppliesToResolved"><q5:VALUE>Value</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassResultCodeValue"><q5:VALUE>0</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassResultCode"><q5:VALUE>0x00000000</q5:VALUE></q5:PROPERTY><q5:PROPERTY NAME="polmkrClassResultText"><q5:VALUE>The operation completed successfully.</q5:VALUE></q5:PROPERTY><q5:Values /><q5:Attributes /><q5:Members /></q5:INSTANCE><q5:Values /><q5:Attributes /><q5:Members /></q5:BaseInstanceXml></q5:RegistryRsopSetting></Extension><Name xmlns="http://www.microsoft.com/GroupPolicy/Settings">Windows Registry</Name></ExtensionData></UserResults></Rsop>


foreach loop is not working

$
0
0

I am right now trying to do a Select String search on all of my files in a particular folder

However I am running into an issue though with the foreach loop, when I run the foreach loop I get this as an ouput:

VERBOSE: Performing the operation "Copy File" on target "Item: C:\Users\test\Documents\Script\temp\TEST1.txt Destination

: C:\Users\test\Documents\Script\Destination1\TEST1.txt".

VERBOSE: Performing the operation "Copy File" on target "Item: C:\Users\test\Documents\Script\temp\TEST1.txt Destination

: C:\Users\test\Documents\Script\Destination1\TEST1.txt".

VERBOSE: Performing the operation "Copy File" on target "Item: C:\Users\test\Documents\Script\temp\TEST1.txt Destination

: C:\Users\test\Documents\Script\Destination1\TEST1.txt".

 

There are 3 different files in this folder, it should be cycling through all of them, not just TEST1

$path1="C:\Users\test\Documents\Script\temp"
$destination1="C:\Users\test\Documents\Script\Destination1"
$destination2="C:\Users\test\Documents\Script\Destination2"
$destination3="C:\Users\test\Documents\Script\Destination3"
$STRING1 = "OUTSIDE"
$STRING2 = "backup"
$files =  Get-ChildItem $path1
$file1 = Select-String -Path $file -pattern $STRING1 -list -CaseSensitive
$filepath1 = $file1 | select -ExpandProperty Path
$file2 = Select-String -Path $file -pattern $STRING2 -list
$filepath2 = $file2 | select -ExpandProperty Path
$file3 = Select-String -Path $file -notmatch $STRING1 -list -CaseSensitive | Select-String -NotMatch $String2
$filepath3 = $file3 | select -ExpandProperty Path
foreach ($file in $files){
if ($file1){
Copy-Item -Path $filepath1 -Destination $destination1 -Verbose}
elseif ($file2){
Copy-Item -Path $filepath2 -Destination $destination2 -Verbose}
elseif ($file3){
Copy-Item -Path $filepath3 -Destination $destination3 -Verbose}
}  


Adding text to open Form

$
0
0

Writing a script for users to copy Outlook PST files from laptop C drives to network drive

----------

#Check whether Outlook is running - if so need to warn user that we will close it down if they click ok

$OutlookisOpen=$false

if (get-process-EA“SilentlyContinue”outlook|where {$_.ProcessName-eq“Outlook”}) {

   $OutlookisOpen =$true

   }

$startcopy=$false

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$objForm=New-Object System.Windows.Forms.Form

$objForm.Text="Copy Outlook PST Files"

$objForm.Size=New-Object System.Drawing.Size(800,600)

$objForm.font=New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Italic)

$objForm.BackColor="Orange"

$objForm.StartPosition="CenterScreen"

# This just allows for Enter or Escape to entered in addition to clicking on OK or Cancel

$objForm.KeyPreview=$True

$objForm.Add_KeyDown({if ($_.KeyCode-eq"Enter")

   {$global:startcopy=$true;$objForm.Close()}})

$objForm.Add_KeyDown({if ($_.KeyCode-eq"Escape")

   {$objForm.Close()}})

$objLabel=New-Object System.Windows.Forms.Label

$objLabel.Location=New-Object System.Drawing.Size(50,50)

$objLabel.Size=New-Object System.Drawing.Size(700,100)

$objLabel.Text="This process takes a long time. You must not shut your computer down or open Outlook whilst the copy process is running"

$objForm.Controls.Add($objLabel)

$objLabel=New-Object System.Windows.Forms.Label

$objLabel.Location=New-Object System.Drawing.Size(50,150)

$objLabel.Size=New-Object System.Drawing.Size(700,100)

if ($OutlookisOpen-eq"True") {

   $objLabel.Text="WARNING: Outlook is currently open. Save your work and click OK to close Outlook and continue or CANCEL to quit"

   }

$objForm.Controls.Add($objLabel)

$ProgressLabel=New-Object System.Windows.Forms.Label

$ProgressLabel.Location=New-Object System.Drawing.Size(50,250)

$ProgressLabel.Size=New-Object System.Drawing.Size(700,100)

$ProgressLabel.Text="Copying File - Please wait..."

$ProgressLabel.Visible=$false

$objForm.Controls.Add($ProgressLabel)

$OKButton=New-Object System.Windows.Forms.Button

$OKButton.Location=New-Object System.Drawing.Size(300,400)

$OKButton.Size=New-Object System.Drawing.Size(100,50)

$OKButton.Text="OK"

$OKbutton.add_Click($OKButton_OnClick)

#$OKButton.Add_Click({$global:startcopy=$true;$objForm.Close()})

$objForm.Controls.Add($OKButton)

$CancelButton=New-Object System.Windows.Forms.Button

$CancelButton.Location=New-Object System.Drawing.Size(425,400)

$CancelButton.Size=New-Object System.Drawing.Size(100,50)

$CancelButton.Text="Cancel"

$CancelButton.Add_Click({$objForm.Close()})

$objForm.Controls.Add($CancelButton)

# This ensure the window is in front

$objForm.Topmost=$True

$objForm.Add_Shown({$objForm.Activate()})

[void]$objForm.ShowDialog()

#------------------------------------------------------------------------------------------

$okbutton_OnClick= {

   # Start the Process

   $PSTLocal ="C:\PSTFiles\"

       

   $PSTRemote ="H:\My Documents\PSTFiles"

   if (!(Test-Path$PSTRemote)) {

       new-item-path$PSTRemote-ItemTypeDirectory

       }

   

   Get-ChildItem $PSTLocal-Recurse -Force|ForEach-Object {

       $ProgressLabel.Visible=$true

       Copy-Item-Path$_.FullName-Destination$PSTRemote

       }

      

   $objForm.Close()

   }

 ---------------

Its a work in progress but essentially working fine. What I am trying to do is to keep the form on screen and to display each file as its being copied with the filename. Therefore I setup the form and text boxes etc. and do the copying process after user clicks on ok button. It copies fine but the $progresslabel text does not display because it appears the form is already open

How can I fix this ?


Ian Burnell, London (UK)

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,

Powershell Script To Create A Folder Than Copy to External HD

$
0
0

Hey guys, 

 First, let me say, I am a complete noob at Powershell. I am looking to create a powershell script and run it as a Scheduled Task. I have an external HD connected to a server. I need to transfer the contents of several folders on the server to an external HD. What I am looking for is the following:

1) Create a folder on the external HD with the date. 

2) Copy the files to this new folder with the date. 

The task would run once a month. 

Thanks in advanced

Where to add the convertto-html

$
0
0

hello,

 I have this script I very slightly modified from "The scripting guys : The Admin’s First Steps: Scan Multiple Event Logs"

$ErrorActionPreference = "SilentlyContinue" # Do you want to surpress all error messages?

$Server = Get-Content C:\servers.txt
$filter = @{
LogName = 'System' # Log file to search
Id = 1128  # Eventlog ID to search for
StartTime = (Get-Date).AddDays(-1)  # How many days to search for, today - X number of days.
}

Foreach ($Computer in $Server) {
New-Object -TypeName PSObject -Property @{
Computer = $Computer
Count = Get-WinEvent -FilterHashtable $filter -Computername $Computer |Measure-Object|Select -ExpandProperty Count
}

}

The script works fine and gives me what I need but not in the format I would like.  I would like the output in an html page.

I tried adding convertto-html in few places but get  garbage output.  Adding in a "Select-object computer, count" before the convertto-html also didn't work..

Any ideas on how to output it to html?

Thanks

Newbie question: How to check ports remotely on a server

$
0
0

I want to check ports of servers in my farm. We used a utility Cruise Control where we can run scripts remotely on a server.

I found a script online to check ports for server:

https://gallery.technet.microsoft.com/scriptcenter/97119ed6-6fb2-446d-98d8-32d823867131

My issue is I don't know how to use it. Script has a function with multiple arguments. 

So to test I copy the script "Test-Port.ps1" to my laptop and try to run it. File was copied to C:\temp

so on dos prompt I switch to dir:

C:\temp> Test-port.ps1 -computername MYserver -Port 80

but it doesn't do anything. I'm not sure how to pass the arguments or parameters to this function from command line.

My goal is to run this on a remote server, passing the destination and port number.

I really apologize I'm new to powershell this must sound a like a very dumb question.

Really appreciate if someone can help me understand how to use this script remotely.

function Test-Port{<#
.SYNOPSIS
    Tests port on computer.

.DESCRIPTION
    Tests port on computer.

.PARAMETER computer
    Name of server to test the port connection on.

.PARAMETER port
    Port to test

.PARAMETER tcp
    Use tcp port

.PARAMETER udp
    Use udp port

.PARAMETER UDPTimeOut
    Sets a timeout for UDP port query. (In milliseconds, Default is 1000)

.PARAMETER TCPTimeOut
    Sets a timeout for TCP port query. (In milliseconds, Default is 1000)

.NOTES
    Name: Test-Port.ps1
    Author: Boe Prox
    DateCreated: 18Aug2010
    List of Ports: http://www.iana.org/assignments/port-numbers

    To Do:
        Add capability to run background jobs for each host to shorten the time to scan.
.LINK
    https://boeprox.wordpress.org

.EXAMPLE
    Test-Port -computer 'server' -port 80
    Checks port 80 on server 'server' to see if it is listening

.EXAMPLE
    'server' | Test-Port -port 80
    Checks port 80 on server 'server' to see if it is listening

.EXAMPLE
    Test-Port -computer @("server1","server2") -port 80
    Checks port 80 on server1 and server2 to see if it is listening

.EXAMPLE
    Test-Port -comp dc1 -port 17 -udp -UDPtimeout 10000

    Server   : dc1
    Port     : 17
    TypePort : UDP
    Open     : True
    Notes    : "My spelling is Wobbly.  It's good spelling but it Wobbles, and the letters
            get in the wrong places." A. A. Milne (1882-1958)

    Description
    -----------
    Queries port 17 (qotd) on the UDP port and returns whether port is open or not

.EXAMPLE
    @("server1","server2") | Test-Port -port 80
    Checks port 80 on server1 and server2 to see if it is listening

.EXAMPLE
    (Get-Content hosts.txt) | Test-Port -port 80
    Checks port 80 on servers in host file to see if it is listening

.EXAMPLE
    Test-Port -computer (Get-Content hosts.txt) -port 80
    Checks port 80 on servers in host file to see if it is listening

.EXAMPLE
    Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
    Checks a range of ports from 1-59 on all servers in the hosts.txt file

#>
[cmdletbinding(
    DefaultParameterSetName = '',
    ConfirmImpact = 'low'
)]
    Param(
        [Parameter(
            Mandatory = $True,
            Position = 0,
            ParameterSetName = '',
            ValueFromPipeline = $True)]
            [array]$computer,
        [Parameter(
            Position = 1,
            Mandatory = $True,
            ParameterSetName = '')]
            [array]$port,
        [Parameter(
            Mandatory = $False,
            ParameterSetName = '')]
            [int]$TCPtimeout=1000,
        [Parameter(
            Mandatory = $False,
            ParameterSetName = '')]
            [int]$UDPtimeout=1000,
        [Parameter(
            Mandatory = $False,
            ParameterSetName = '')]
            [switch]$TCP,
        [Parameter(
            Mandatory = $False,
            ParameterSetName = '')]
            [switch]$UDP
        )
    Begin {
        If (!$tcp -AND !$udp) {$tcp = $True}
        #Typically you never do this, but in this case I felt it was for the benefit of the function
        #as any errors will be noted in the output of the report
        $ErrorActionPreference = "SilentlyContinue"
        $report = @()
    }
    Process {
        ForEach ($c in $computer) {
            ForEach ($p in $port) {
                If ($tcp) {
                    #Create temporary holder
                    $temp = "" | Select Server, Port, TypePort, Open, Notes
                    #Create object for connecting to port on computer
                    $tcpobject = new-Object system.Net.Sockets.TcpClient
                    #Connect to remote machine's port
                    $connect = $tcpobject.BeginConnect($c,$p,$null,$null)
                    #Configure a timeout before quitting
                    $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
                    #If timeout
                    If(!$wait) {
                        #Close connection
                        $tcpobject.Close()
                        Write-Verbose "Connection Timeout"
                        #Build report
                        $temp.Server = $c
                        $temp.Port = $p
                        $temp.TypePort = "TCP"
                        $temp.Open = "False"
                        $temp.Notes = "Connection to Port Timed Out"
                    } Else {
                        $error.Clear()
                        $tcpobject.EndConnect($connect) | out-Null
                        #If error
                        If($error[0]){
                            #Begin making error more readable in report
                            [string]$string = ($error[0].exception).message
                            $message = (($string.split(":")[1]).replace('"',"")).TrimStart()
                            $failed = $true
                        }
                        #Close connection
                        $tcpobject.Close()
                        #If unable to query port to due failure
                        If($failed){
                            #Build report
                            $temp.Server = $c
                            $temp.Port = $p
                            $temp.TypePort = "TCP"
                            $temp.Open = "False"
                            $temp.Notes = "$message"
                        } Else{
                            #Build report
                            $temp.Server = $c
                            $temp.Port = $p
                            $temp.TypePort = "TCP"
                            $temp.Open = "True"
                            $temp.Notes = ""
                        }
                    }
                    #Reset failed value
                    $failed = $Null
                    #Merge temp array with report
                    $report += $temp
                }
                If ($udp) {
                    #Create temporary holder
                    $temp = "" | Select Server, Port, TypePort, Open, Notes
                    #Create object for connecting to port on computer
                    $udpobject = new-Object system.Net.Sockets.Udpclient
                    #Set a timeout on receiving message
                    $udpobject.client.ReceiveTimeout = $UDPTimeout
                    #Connect to remote machine's port
                    Write-Verbose "Making UDP connection to remote server"
                    $udpobject.Connect("$c",$p)
                    #Sends a message to the host to which you have connected.
                    Write-Verbose "Sending message to remote host"
                    $a = new-object system.text.asciiencoding
                    $byte = $a.GetBytes("$(Get-Date)")
                    [void]$udpobject.Send($byte,$byte.length)
                    #IPEndPoint object will allow us to read datagrams sent from any source.
                    Write-Verbose "Creating remote endpoint"
                    $remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
                    Try {
                        #Blocks until a message returns on this socket from a remote host.
                        Write-Verbose "Waiting for message return"
                        $receivebytes = $udpobject.Receive([ref]$remoteendpoint)
                        [string]$returndata = $a.GetString($receivebytes)
                        If ($returndata) {
                           Write-Verbose "Connection Successful"
                            #Build report
                            $temp.Server = $c
                            $temp.Port = $p
                            $temp.TypePort = "UDP"
                            $temp.Open = "True"
                            $temp.Notes = $returndata
                            $udpobject.close()
                        }
                    } Catch {
                        If ($Error[0].ToString() -match "\bRespond after a period of time\b") {
                            #Close connection
                            $udpobject.Close()
                            #Make sure that the host is online and not a false positive that it is open
                            If (Test-Connection -comp $c -count 1 -quiet) {
                                Write-Verbose "Connection Open"
                                #Build report
                                $temp.Server = $c
                                $temp.Port = $p
                                $temp.TypePort = "UDP"
                                $temp.Open = "True"
                                $temp.Notes = ""
                            } Else {<#
                                It is possible that the host is not online or that the host is online,
                                but ICMP is blocked by a firewall and this port is actually open.
                                #>
                                Write-Verbose "Host maybe unavailable"
                                #Build report
                                $temp.Server = $c
                                $temp.Port = $p
                                $temp.TypePort = "UDP"
                                $temp.Open = "False"
                                $temp.Notes = "Unable to verify if port is open or if host is unavailable."
                            }
                        } ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) {
                            #Close connection
                            $udpobject.Close()
                            Write-Verbose "Connection Timeout"
                            #Build report
                            $temp.Server = $c
                            $temp.Port = $p
                            $temp.TypePort = "UDP"
                            $temp.Open = "False"
                            $temp.Notes = "Connection to Port Timed Out"
                        } Else {
                            $udpobject.close()
                        }
                    }
                    #Merge temp array with report
                    $report += $temp
                }
            }
        }
    }
    End {
        #Generate Report
        $report
    }
}

 

Help in understanding some PowerShell script?

$
0
0

Hi All

Im pretty rusty with PowerShell scripting.  I have inherited a script which I need to modify its behaviour such that it uses a 10 hour window rather than the current 9 hour window (script as a whole is runnign fine at the moment).  However Im struggling to get detail on some of the switches used below (-ge, -le and -ne).

Any help in understanding the below would be much appreciated!

if (((get-date).timeofday.totalminutes -ge 899) -and ((get-date.timeofday.totalminutes -le 1021) -and ((get-date).dayofweek -ne "Saturday"))




Distribution Group - Mangedby (array)

$
0
0

Hello,

Not sure if this is the correct location or if this should be posted on an Office 365 board.  If not I apologize for that, but I am looking for a way export all the distribution groups we have in office 365 and display the managedby array.  I haven't found a way to export it so I can see all the users in that array.  When I run

Get-DistributionGroup -Identity "NameGroup" |ft -autosize -Property managedby

I get {user1, user2, user3, user4...} and it won't display the rest of the users.  Any help or tips would be great.  I am still fairly new with powershell and trying to learn as I go.

Thanks,

Joe


Reproduce Functionality of Windows Vista/7's "timeout.exe"

$
0
0

I'm aware of PowerShell's Start-Sleep cmdlet , but, from what I can tell, there's no way for the user to interrupt the pause created by the Start-Sleep cmdlet like they can with Windows Vista/7's "timeout.exe". Is there a way for a PowerShell script to behave like Windows Vista/7's "timeout.exe" without using "timeout.exe" itself? I'd like this to work on Windows XP as well.


Thanks!

can not execute tpm32 class commands using

$
0
0

Hi, I am using the wmic to display some information of tpm device installed onto system.

From win32 class I see there are properties and methods available.

I am able to issue and display properties of win32 class however calling the method is not working.

For properties I have to get and methods it appears it is call.

But none of the methods work with call.

Below is example is counter-logical to each other:

isEnabled is supposed to be called without parameter with or without the parameter it displays error message that is counter-logical. Am I doing wrong or is this class broken?

PS C:\Users\Administrator> wmic /namespace:\\root\cimv2\security\microsofttpm path win32_tpm call isEnabled
Executing (win32_tpm)->isEnabled()
ERROR:
Description = Invalid method Parameter(s)
PS C:\Users\Administrator> wmic /namespace:\\root\cimv2\security\microsofttpm path win32_tpm call isEnabled 0
Verb Or Method has no input parameters.








Need import module from remote PC

$
0
0

Need to import modules from PC which is located in remote PC.

invoke ie for an siteminder enable site

$
0
0

Hi All,

I have the required to parse some web data from a siteminder enabled website.
I have tried using system.net.webclient with alternate credentials but no luck. The site first tries to load the siteminder authentication challenge and then redirects to the actual page.

Please help me with any hint or suggestions of how I can achieve this.

Thanks
Neo

invoke-command 'Write-Host' is not recognized as the name of a cmdlet,

$
0
0

Is it possible to run generic cmdlets and exchange 2010 cmdletss in remote session via scriptblock in one scriptblock?


$s = New-PSSession  -ConfigurationName Microsoft.Exchange -ConnectionUri http://xxx/PowerShell/ -Authentication Kerberos –AllowRedirection

Invoke-Command -Session $s -scriptblock { write-host a;get-transportserver xxx* }
Remove-PSSession $s


The term 'Write-Host' is not recognized as the name of a cmdlet,


I need to run script in Parallel via Invoke-Command script https://gallery.technet.microsoft.com/office/Exchange-2010-Public-944df6ee - public folder report.  Is there better way than run script by https://gallery.technet.microsoft.com/scriptcenter/Run-Parallel-Parallel-377fd430 ?

$test = @()

$test = Invoke-Parallel -InputObject $servers -throttle 20 -LogFile .\test.txt {
$s = New-PSSession  -ConfigurationName Microsoft.Exchange -ConnectionUri http://$_/PowerShell/ -Authentication Kerberos
$Computername = $_
$FolderPath = "xxx"
$ProgramName = "C:\PublicFolders\PublicFolders.ps1"
Invoke-Command -Session $s -scriptblock {param($Comp, $PathFolder, $program) &$program -computername $Comp -FolderPath $PathFolder} -ArgumentList $Computername, $FolderPath, $ProgramName
Remove-PSSession $s
}

PublicFolders.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program





Viewing all 21975 articles
Browse latest View live


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