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

Check if string starts with letter/character.

$
0
0

Hey Guys,

Working on a user input piece, and I need to validate that the first character in the string is a letter.  I've been dinking around with -

               

$inputbox = [Microsoft.VisualBasic.Interaction]::InputBox("Please enter your Site location:", "Test Script")


if(!($inputbox.StartsWith("[a-z]^[A-Z]")){

do{
$inputbox = [Microsoft.VisualBasic.Interaction]::InputBox("Your site location should start with a letter and be $len characters long.  Please enter your Site location:", "Test Script")
}while(!($inputbox.StartsWith("[a-z]^[A-Z]"))
}

I feel like what I have above will only check if it starts with a.  I could do something like this as well but not sure -

($inputbox[0] -notmatch "[a-z]^[A-Z]")

I could create an alphabet array and loop through that against [0] as well? Any other elegant ways to handle this?  Thanks :)

Ryan


Split and join with leading zeros

$
0
0

Hi All,

I am a little bit struggling with splitting and joining an IP address. What I want to do for practice is to split an IP address (for example: 10.0.101.23) split it in 4 parts. Take the last 3 parts and at leading zeros for each part to have a total of 9 numbers. For the example this would be 000101023. I know how I can split. How I can add leading zeros and how to join. But not how to use this is an effective way together.

The parts I have:

$IP = "10.0.101.23"
$IPS = $IP.Split(".")
$IPS =  "$($IPS[1])$($IPS[2])$($IPS[3])"

$a.ToString("000") <- Not working because it is not a string. Do I need to create an array?

Thanks, Bart

Enable or Disable based on if something is checked in CheckedListBox

$
0
0

So I have some code that was generated from PrimalForms to develop a GUI.  This is a simple GUI I created to keep my question simple.

This GUI has 2 CheckedListBox's  $Testbox1 and $Testbox2.  $Testbox2 is Diabled by default.  I want $Testbox2 to Enable once someone checks something in $Testbox1 (For Example: someone checks "test1").  Then I want $Testbox2 to Disable again if that same user UnChecks "Test1".

Now keep in mind, a CheckedListBox allows for more than 1 item to be checked.  That being said, $Testbox2 should remain enabled so long as SOMETHING is checked in $Testbox1 but disabled if NOTHING is checked in $Testbox1.

What I have so far is, when placing a Check on an item in $Testbox1, $Testbox2 gets enabled.  If I uncheck everything in $Testbox1, $Testbox2 still remains enabled.  Which is what I don't want.  Here is the code: (Any help would be greatly appreciated)

#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 9/16/2015 12:02 PM
# Generated By: tbrown
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$testbox2 = New-Object System.Windows.Forms.CheckedListBox
$TestBox1 = New-Object System.Windows.Forms.CheckedListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 223
$System_Drawing_Size.Width = 142
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = "form1"
$form1.Text = "Primal Form"

$testbox2.CheckOnClick = $True
$testbox2.DataBindings.DefaultDataSourceUpdateMode = 0
$testbox2.Enabled = $False
$testbox2.FormattingEnabled = $True
$testbox2.Items.Add("whatever1")|Out-Null
$testbox2.Items.Add("whatever2")|Out-Null
$testbox2.Items.Add("whatever3")|Out-Null
$testbox2.Items.Add("whatever4")|Out-Null
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 16
$System_Drawing_Point.Y = 123
$testbox2.Location = $System_Drawing_Point
$testbox2.Name = "testbox2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 79
$System_Drawing_Size.Width = 85
$testbox2.Size = $System_Drawing_Size
$testbox2.TabIndex = 1

$form1.Controls.Add($testbox2)

$TestBox1.CheckOnClick = $True
$TestBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$TestBox1.FormattingEnabled = $True
$TestBox1.Items.Add("test1")|Out-Null
$TestBox1.Items.Add("test2")|Out-Null
$TestBox1.Items.Add("test3")|Out-Null
$TestBox1.Items.Add("test4")|Out-Null
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 17
$System_Drawing_Point.Y = 13
$TestBox1.Location = $System_Drawing_Point
$TestBox1.Name = "TestBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 79
$System_Drawing_Size.Width = 67
$TestBox1.Size = $System_Drawing_Size
$TestBox1.TabIndex = 0
$Testbox1.Add_Click({$testbox2.Enabled = $True})

$form1.Controls.Add($TestBox1)

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm


How to gather inputs from a form

$
0
0
################################## Import ActiveDirectory ##############################################

Import-Module ActiveDirectory

################################## Import Exchange snap-in #############################################

#Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin

########################################################################################################

clear-host
[System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
[System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object “System.Windows.Forms.Form”;
$form.Width = 500;
$form.Height = 350;
$Form.Autosize = $True
$form.Text = "New AD User Creation";
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
$Form.Topmost = $True

##############Define text label1
$textLabel1 = New-Object “System.Windows.Forms.Label”;
$textLabel1.Left = 25;
$textLabel1.Top = 15;

$textLabel1.Text = "Username to Copy";

##############Define text label2

$textLabel2 = New-Object “System.Windows.Forms.Label”;
$textLabel2.Left = 25;
$textLabel2.Top = 50;
$textLabel2.Autosize = $True
$textLabel2.Text = "Requested Username";

##############Define text label3

$textLabel3 = New-Object “System.Windows.Forms.Label”;
$textLabel3.Left = 25;
$textLabel3.Top = 95;

$textLabel3.Text = "User First Name";

##############Define text label4

$textLabel4 = New-Object “System.Windows.Forms.Label”;
$textLabel4.Left = 25;
$textLabel4.Top = 135;

$textLabel4.Text = "User Last Name";

##############Define text label5

$textLabel5 = New-Object “System.Windows.Forms.Label”;
$textLabel5.Left = 25;
$textLabel5.Top = 175;

$textLabel5.Text = "Newuser logon";



############Define text box1 for input
$textBox1 = New-Object “System.Windows.Forms.TextBox”;
$textBox1.Left = 200;
$textBox1.Top = 10;
$textBox1.width = 200;

############Define text box2 for input

$textBox2 = New-Object “System.Windows.Forms.TextBox”;
$textBox2.Left = 200;
$textBox2.Top = 50;
$textBox2.width = 200;

############Define text box3 for input

$textBox3 = New-Object “System.Windows.Forms.TextBox”;
$textBox3.Left = 200;
$textBox3.Top = 90;
$textBox3.width = 200;

############Define text box4 for input

$textBox4 = New-Object “System.Windows.Forms.TextBox”;
$textBox4.Left = 200;
$textBox4.Top = 130;
$textBox4.width = 200;

############Define text box4 for input

$textBox5 = New-Object “System.Windows.Forms.TextBox”;
$textBox5.Left = 200;
$textBox5.Top = 170;
$textBox5.width = 200;

#############Define default values for the input boxes
$defaultValue = “”
$textBox1.Text = $defaultValue;
$textBox2.Text = $defaultValue;
$textBox3.Text = $defaultValue;
$textBox4.Text = $defaultValue;
$textBox5.Text = $defaultValue;

###########Connecting Enter and Escape Keys to buttons
$Form.KeyPreview = $True
$Form.Add_KeyDown({if ($_.Keycode -eq "Enter") {$x=$Form.Text;$Form.Close()}})
$Form.Add_KeyDown({if ($_.Keycode -eq "Escape") {$Form.Close()}})


###########OK button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(200,220)
$OKButton.Size = New-Object System.Drawing.Size(50,35)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$Form.Close()})


###########Cancel Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(340,220)
$CancelButton.Size = New-Object System.Drawing.Size(65,35)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$Form.Close()})


############# This is when you have to close the form after getting values
$eventHandler = [System.EventHandler]{
$textBox1.Text;
$textBox2.Text;
$textBox3.Text;
$textBox4.Text;
$textBox5.Text;
$form.Close();};
$button.Add_Click($eventHandler);

#############Add controls to all the above objects defined
$Form.Controls.Add($CancelButton);
$Form.Controls.Add($OKButton);
$form.Controls.Add($textLabel1);
$form.Controls.Add($textLabel2);
$form.Controls.Add($textLabel3);
$form.Controls.Add($textLabel4);
$form.Controls.Add($textLabel5);
$form.Controls.Add($textBox1);
$form.Controls.Add($textBox2);
$form.Controls.Add($textBox3);
$form.Controls.Add($textBox4);
$form.Controls.Add($textBox5);
$ret = $form.ShowDialog();



    $x = $textBox.Text
    $x


#################return values

return $textBox1.Text, $textBox2.Text, $textBox3.Text, $textBox4.Text, $textbox5.Text


$return= button “User to Copy” “Requested Username” “User Firstname” “User Lastname” "Re-enter user logon name"

Below variables will get the values that had been entered by the user

$return[0]
$return[1]
$return[2]
$return[3]
$return[4]




# Gets all of the users info to be copied to the new account
#Checking the user to copy if it exist

do {
$nameds = "$textBox1.Text"
if (dsquery user -samid $nameds){"AD User Found"
}

elseif ($nameds = "null") {"AD User not Found"}
}
while ($nameds -eq "null")

#Checking if the new user exist

do {

$NewUserds = "$textBox2.Text"

While ( $NewUserds -eq "" ) { $NewUserds = "$textBox2.Text"}
$NewUser = $Newuserds

if (dsquery user -samid $NewUserds){"The AD Username entered is currently in use"}

elseif ($NewUserds = "no") {"Username is available for use"}
}

while ($Newuserds -ne "no")

# Gets all of the users info to be copied to the new account

$name = Get-AdUser -Identity $nameds -Properties *

$DN = $name.distinguishedName
$OldUser = [ADSI]"LDAP://$DN"
$Parent = $OldUser.Parent
$OU = [ADSI]$Parent
$OUDN = $OU.distinguishedName
$NewUser = "$textBox2.Text"
$firstname = "$textBox3.Text"
$Lastname = "$textBox4.Text"
$NewName = "$firstname $lastname"
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() 
$Displayname = "$FirstName.$LastName"
$Display = "$LastName, $firstname"


# Creates the user from the copied properties

New-ADUser -SamAccountName $NewUser -Name $Display -GivenName $firstname -Surname $lastname -Instance $DN -Path "$OUDN" -DisplayName $Display -AccountPassword (Read-Host "New Password" -AsSecureString) –userPrincipalName $Displayname@$domain -Company $name.Company -Department $name.Department -Manager $name.Manager -title $name.Title -Description (Read-Host "Please Enter a Description") -Office $name.Office -City $name.city -PostalCode $name.postalcode -Country $name.country -OfficePhone $name.OfficePhone -Fax $name.fax -State $name.State -StreetAddress $name.StreetAddress -Enabled $true 

# Creates the special attributes

#Get-ADUser  $NewUser -Properties mail,mailNickname, proxyAddresses, targetAddress, GivenName, Surname
Set-aduser $NewUser -Add @{proxyAddresses = "SMTP:$Displayname@hillphoenix.com", "smtp:$Displayname-hillphoenix-com@dover.mail.onmicrosoft.com"; Mail = "$Displayname@hillphoenix.com"; mailNickName = "$Displayname"; targetAddress = "SMTP:$Displayname-HillPHOENIX-com@dover.mail.onmicrosoft.com"}

# gets groups from the Copied user and populates the new user in them

write-host "Copying Group Membership"

$groups = (GET-ADUSER –Identity $name –Properties MemberOf).MemberOf
foreach ($group in $groups) { 

Add-ADGroupMember -Identity $group -Members $NewUser
}
$count = $groups.count


Write-host "New User Mail Parameters"

Get-ADUser  $NewUser -Properties mail,mailNickname, proxyAddresses, targetAddress, GivenName, Surname

AD and GP modules are not showing on Domain Controller

$
0
0
I am needing to update GP on client computers across their domain. I have been trying to use Powershell to push gpupdate across the domain but I cannot import AD or GP modules into powershell. The server is 2008 Standard FE with SP2. Under System32/wps/v1.0/modules I only see BitsTransfer and PSDiagnostics. I have been looking everywhere to download the GP and AD module to install onto the server but I have found nothing but help for using powershell on Windows 7 machines. Also, there is no powershell folder under my documents. The client is using redirected folders for everyone. I either need the modules to manually install them or a fix to use the modules in powershell. I cannot use any GP or AD cmdlets and cannot import them because there is nothing to import.

script check Certificate Revocation List -CRL time update

$
0
0
I have a digital certificate (Certificate Revocation List -CRL) is updated automatically every day.
Seated documents:
\\ sherefoleder \ certificate \ certificate.crl
I am looking for a script to do a test every day the date of the digital certificate are of the same day
Thank you

אם תגובתי פתרה את בעייתך - לחץ/י, על &quot;סמן כתשובה&quot; ליד סימן ה V הירוק.

Powershell 4: Start-Transcript does not log Write-Host

$
0
0

Hi, 

After creating an instance of the latest Windows Server 2012 R2 image on Windows Azure, we see a strange issue with Powershell transcripts: Write-Host is not transcribed. However, "foobar" | Out-Host IS transcribed! Very strange. However, both Write-Warning, and any errors (exceptions, or write-error) does give output.

Anyone else seen this issue? Is this expected behavior or a bug?

Thanks a lot in advance! :-)

Sincerely,

Hallgeir

Here's my powershell version info:

PS C:\> $psversiontable

Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34014
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

Example:

**********************
Windows PowerShell transcript start
Start time: 20150114143638
Username: xxx\xxx
RunAs User: xxx\xxx
Machine: xxx (Microsoft Windows NT 6.3.9600.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 2160
**********************
Transcript started, output file is C:\foobar.txt

PS C:\> Write-Host "This is a test"

            CurrentMatchIndex              ReplacementIndex             ReplacementLength CompletionMatches
            -----------------              ----------------             ----------------- -----------------
                           -1                             0                            12 {System.Management.Automat...



PS C:\> Stop-Transcript
**********************
Windows PowerShell transcript end
End time: 20150114143658
**********************

Here's how it looks with piping to Out-Host:

**********************
Windows PowerShell transcript start
Start time: 20150114143755
Username: xxx\xxx
RunAs User: xxx\xxx
Machine: xxx (Microsoft Windows NT 6.3.9600.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 2160
**********************
Transcript started, output file is C:\foobar.txt

            CurrentMatchIndex              ReplacementIndex             ReplacementLength CompletionMatches
            -----------------              ----------------             ----------------- -----------------
                           -1                            19                             8 {System.Management.Automat...



PS C:\> "This is a test" | Out-Host
This is a test

            CurrentMatchIndex              ReplacementIndex             ReplacementLength CompletionMatches
            -----------------              ----------------             ----------------- -----------------
                           -1                             0                             9 {System.Management.Automat...



PS C:\> Stop-Transcript
**********************
Windows PowerShell transcript end
End time: 20150114143809
**********************


Delayed output of powershell

$
0
0

Hello,

I have experienced a weird behavior of powershell scripting. My script is not running sequentially (row per row) but the order of rows are being ran randomly. 

PS version is 3.0, win 2012 R2

maybe the picture below will describe it better

http://snag.gy/ZULfa.jpg (my account is not verified so I cannot paste the image here)

How it should look like?

                                            

Current IDs which are not allowed: 

DeviceId                   DeviceAccessState
--------                   -----------------
MLC556T6U57R30B9UP524KQN1C Quarantined      
5T3L57GPVL4PLE1SEKNEGTUH1O Quarantined      
1595486682                 Allowed          

Want to continue?
What device do you want to take out from quarantine? [0/1-x]
0

Have somebody experienced the same issue? Have tried almost everything. Changed the switch to multiple ifs, removed the function, tried to run the script on separate window but with the same results.

Best regards,

An.


Trying to Monitor dirsync time with powershell script

$
0
0

Hello,

I'm trying to get a monitor for PRTG to alert us if the dirsync application has not synced in over 4 hours. I'm having an issue with the output from PowerShell command.

Here is what I have for the powershell script so far.

$username = "admin1@contoso.onmicrosoft.com"
$password = "********"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))

Import-Module MSOnline
Connect-MsolService -Credential $Cred `
  -WarningAction SilentlyContinue

get-MsolCompanyInformation | select LastDirSyncTime | ft -HideTableHeaders

and it is working. It gives me output that I understand, however it is not a true date and time output but just a text output.

"6/1/2015 3:29:50 PM"

How can I get that output to a real data and time to run a comparison on it to verify that it has synced?

Update McAfee Dat on multiple remote servers

$
0
0

Hi All, am new to PS scripting, i have a small requirement , i need to update mcafee dat on multiple remote servers without login to them, so with PS script i tried with following code but it is not working , can someone help me to correct this.

$RemoteServers = Get-Content "c:\logs\McAfee\Servers.txt"

        @(

           foreach ($Server in $RemoteServers)

          {

            if ( Test-Connection -ComputerName $RemoteServer -Count 1 -ErrorAction SilentlyContinue )

            {

              

              $Path='c:\Program Files (x86)\McAfee\VirusScan Enterprise\mcupdate.exe'

              $parameters='/update /quiet'

              $Path='c:\Program Files (x86)\McAfee\Common Framework\CmdAgent.exe /p'

            }

            else

            {

            $Path='C:\Program Files\Mcafee\VirusScan Enterprise\mcupdate.exe'

            $Parameters='/update /quiet'

            $Path='c:\Program Files\McAfee\Common Framework\CmdAgent.exe /p'

            Write-Output "$name is unrechable please check the server either from ilo or VC console"

            }

          }

            )|Out-File -FilePath 'c:\logs\McAfee\McAfe_DAT.Update.csv'

 


Issue Importing multiple IP's into firewall via NETSH

$
0
0

I am attempting to create a PowerShell script to add ip addresses to an existing Firewall rule. When I run the following only the last entry is ever added to the firewall rule.

$IPs = @("159.55.107.71", "159.55.110.45", "10.38.82.183", "10.208.165.147", "10.241.186.232", "10.241.186.234", "10.17.98.232", 
"10.211.106.92", "10.208.96.181", "10.208.35.191") |`
   Foreach-object {
   netsh advfirewall firewall set rule name="Existing Firewall Rule" new remoteip="$_"
   write-host "$_ Added $?"
}

When the script completes it shows that it has added every ip but when I check the rule I only see the last ip address in the script.

I have tried removing the brackets and spaces and adding /32 to the end and none of those options worked to add the range.

Hopefully someone can point me in the direction of where I went wrong.

Scheduled Task - Trigerred by Event - Getting data into the scripts as parameters...- Question

$
0
0
Hello - I have event ID - let say password reset (4720 or any other). I have attached the task to the event, so whenever admin is resetting a password the task can trigger power-shell script. Now - the question: How to pass the data from this event using task scheduler into the power-shell script? Thanks for help...

Add a line in text file.

$
0
0

Hi there,

I am trying to put together a script that adds a line to multiple texts files that I have. I have 800 texts files that I want the scripts to go through.

I want the script to search multiple text files, and check if the Terminalname starts with ZT and ends with W. If this is true to  add the following line in the wireless section."Roam =Yes"

;*************************************************************
;*                           Network                         *
;*************************************************************
;ASSET=92148
Terminalname=ZTDUR92148W
SignOn=yes IconGroupStyle=folder
RegisterWINS=yes

;*************************************************************
;*                     Wireless / 802.1x                     *
;*************************************************************

IEEE8021X=yes network=wireless access=WPA2-ENT eap=yes eaptype=EAP-PEAP peapeap=EAP-MSCHAPV2  peapmschappwdEnc=MMDONLBAJOAJNLEOJJFHLMCJPL peapmschapdm=ESGA
Device=Wireless Mode=Infrastructure SSID=SafeATA Channel=6

Roam =Yes

;*************************************************************
;*                      General 2 Special                    *
;*************************************************************

Exit=All

Thanks

Need to check tls/ssl but getting stuck with "You must provide a value expression on the right-hand side of the '-' operator."

$
0
0

I would like to disable ssl 3 but need to test what sites only support ssl 3. I keep getting stuck with an error that is over my head. I've tried manipulating the string a dozen different ways and keep getting the same error. I am not familiar with -notin or how to specify which part of the property its checking: thanks a ton

http://blog.whatsupduck.net/2014/10/checking-ssl-and-tls-versions-with-powershell.html

line with issues:

$ProtocolNames = [System.Security.Authentication.SslProtocols] | gm -static -MemberType Property | where-object{$_.Name -notin @("Default","None") | %{$_.Name}

You must provide a value expression on the right-hand side of the '-' operator.
At S:\scripts\test23.ps1:50 char:126+     $ProtocolNames = [System.Security.Authentication.SslProtocols] | gm -static -MemberType Property | where-object{$_.Name - <<<< noti
n @("Default","None") | %{$_.Name}+ CategoryInfo          : ParserError: (:) [], ParseException+ FullyQualifiedErrorId : ExpectedValueExpression

<#
.DESCRIPTION
  Outputs the SSL protocols that the client is able to successfully use to connect to a server.

.NOTES

  Copyright 2014 Chris Duck
  http://blog.whatsupduck.net

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

.PARAMETER ComputerName
  The name of the remote computer to connect to.

.PARAMETER Port
  The remote port to connect to. The default is 443.

.EXAMPLE
  Test-SslProtocols -ComputerName "www.google.com"

  ComputerName       : www.google.com
  Port               : 443
  KeyLength          : 2048
  SignatureAlgorithm : rsa-sha1
  Ssl2               : False
  Ssl3               : True
  Tls                : True
  Tls11              : True
  Tls12              : True
#>
function Test-SslProtocols {
  param(
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    $ComputerName,

    [Parameter(ValueFromPipelineByPropertyName=$true)]
    [int]$Port = 443
  )
  begin {
    $ProtocolNames = [System.Security.Authentication.SslProtocols] | gm -static -MemberType Property | where-object{$_.Name -notin @("Default","None") | %{$_.Name}
  }
  process {
    $ProtocolStatus = [Ordered]@{}
    $ProtocolStatus.Add("ComputerName", $ComputerName)
    $ProtocolStatus.Add("Port", $Port)
    $ProtocolStatus.Add("KeyLength", $null)
    $ProtocolStatus.Add("SignatureAlgorithm", $null)

    $ProtocolNames | %{
      $ProtocolName = $_
      $Socket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
      $Socket.Connect($ComputerName, $Port)
      try {
        $NetStream = New-Object System.Net.Sockets.NetworkStream($Socket, $true)
        $SslStream = New-Object System.Net.Security.SslStream($NetStream, $true)
        $SslStream.AuthenticateAsClient($ComputerName,  $null, $ProtocolName, $false )
        $RemoteCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]$SslStream.RemoteCertificate
        $ProtocolStatus["KeyLength"] = $RemoteCertificate.PublicKey.Key.KeySize
        $ProtocolStatus["SignatureAlgorithm"] = $RemoteCertificate.PublicKey.Key.SignatureAlgorithm.Split("#")[1]
        $ProtocolStatus.Add($ProtocolName, $true)
      } catch  {
        $ProtocolStatus.Add($ProtocolName, $false)
      } finally {
        $SslStream.Close()
      }
    }
    [PSCustomObject]$ProtocolStatus
  }
}

Test-SslProtocols -ComputerName "www.google.com"


Get-ADuser with imput from array after a split

$
0
0

Hi,

I have a source text file with some records and each having two fields, a URL and a mail address.
Now I need that mail address to perform a search in AD for get the SamAccountName that corresponds with that e-mail address.

https://test.be,first.name@belgium.be
https://test2.be,second.name@belgium.be

Get-Content “C:\Temp\inputdata.txt” | %{$data = $_.split(",")} | ForEach-Object{Get-ADUser -Filter {mail -Like $data[1]} -Verbose -SearchBase "OU=something.be,OU=host,DC=test" -Properties * | Select UserPrincipalName,SamAccountName,mail} | out-file "c:\temp\result.txt"

I do not get an error message. Just no result. Although I am sure it exists. If only have one field in the source file, no problem. Then it works fine.
Get-Content “C:\Temp\onlyemail.txt” | ForEach-Object{Get-ADUser -Filter {mail -Like $_} -Verbose -SearchBase "OU=something.be,OU=host,DC=test" -Properties mail | Select UserPrincipalName,SamAccountName,mail} | out-file "c:\temp\result.txt"

I am also sure that the Split is working.  $data[1] gives me first.name@belgium.be
It must be something with passing that $data[1] in the next part of the pipe.  I think the in the {mail -Like $data[1]}...

Can someone help me out ?
Thanks a lot !


Powershell and SCCM

$
0
0
I have scoured the Internet with no luck.  Anyone out there no how to get the Manufacturer Information of a PC from SCCM (i.e. - the same wmi info stored locally) using Powershell?  Not even sure if this is the right forum for this question. Thanks.  

Matt Dillon

PowerShell Script to update fields in Sharepoint 3.0

$
0
0

Hello everyone!!!

We're using Sharepoint 3.0 to allow users to open help desk tickets with the IT department.  We need to see how many days a ticket has been open.  To do this, we need to update the TodayDate field with the current date so that another field (Age In Days) will show how many days the ticket has been open.

I found this PowerShell script that looks like it would help, but I'm still new to PS a bit.  I know it needs to be updated with our particular site information.  Can anyone possibly break this script down and tell me exactly what it's doing?

Start-SPAssignment-Global
$SPWeb= Get-SPWebhttp://site
$List= $SPWeb.Lists["My Form Lib"]
$Items= $List.Items
foreach($itemin $items) {
$modifiedBy= $item["Editor"]
$formStatus= $item["Form Status"]
if($formStatus-ne"Rejected"-and$formStatus-ne"Completed")
{
$item["TodaysDate"] =Get-Date
$item["Editor"] = $modifiedBy
$item.Update()
$list.Update()
}
}
$SPWeb.Dispose()
Stop-SPAssignment-Global

PowerShell and object disposing

$
0
0

So I know I need to dispose iDisposable objects when I'm done with them. In the .NET SharePoint world, disposing site and web objects is routine and expected to avoid memory leaks.

In PowerShell, I've noticed some unexpected behavior, for instance:

Add-PSSnapin Microsoft.SharePoint.PowerShell

$site = Get-SPSite <yourUrlToSiteCollection>
$web = $site.OpenWeb()

$web.Dispose()
$site.Dispose()

$list = $web.Lists["Announcements"]
$item = $list.Items.Add()
$item["Title"] = "New Announcement!"
$item.Update()

This creates a new announcement, despite the fact the web and site objects have been disposed. Anyone have an explanation as to why this behaves this way? I'd love some insight on to how it's actually handling the objects.

Question on get-aduser and properties

$
0
0

I am fairly new to PowerShell and have gotten quite a bit of help browsing the Forums and asking questions.

I have been working on getting Properties from get-aduser, and its bafflilng to me on the below examples.

To find if a user account is enabled I have used:

get-aduser -identity USERNAME | %{$_.enabled}

   This will return True or False

To check if a user account is Locked I found this will return True or False

(get-aduser -identity USERNAME -Properties LockedOut).LockedOut

Why is this?  When I try

get-aduser -identity USERNAME | %{$_.LockedOut}, it returns blank

Subsequently if I try

(get-aduser -identity USERNAME -Properties Enabled).Enabled, it returns blank.

Its the simple things that drive me crazy. Get-Adcomputer

$
0
0

I needed to write up a simple script as I cannot find my old script to find all Servers then via Test-Connection find if they are active. 

The script works for what it is used for, but when using Add-Content to add the name to the a CSV I get the Distinguished Name when all I want is the name.

Using Write-Host $server.name I get NameofServer

Add-Content $file -Value "$server.name, Is Active" -encoding ascii my csv has the Distinguished Name.

To gather my list

$server = Get-ADComputer - LDAPFilter "(OperatingSystem=*Server*)"

I have staring at the screen to long today, Im sure.

Viewing all 21975 articles
Browse latest View live


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