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

Comparing two text files content

$
0
0

Hi,

I was tasked to create a maintenance script for SCOM. One of the requirements is to read a hardcoded text file called 'ExclusionList.txt'. Then read another text file that the user can drag and drop to the screen, ie: CollectionFile.txt.

ExclusionList.txt are servers that cannot be put into maintenance mode. Whereas CollectionFile.txt can be put into maintenance mode as long as they are not in the ExclusionList.txt. I have tried to do it in powershell but I am not able to get the proper output in CollectionFile. It returns nothing in CollectionFile with the '<=' SideIndicator. I want the result of the items in $CollectionFile to be stored in an array.

$SCOMExclusionFile = Get-Content "C:\Temp\SCOM\ExclusionList.txt"
    
$file_name_input = Read-host "`nDrag and Drop file here"  
if ($file_name_input) { $CollectionFile= $file_name_input }

Compare-Object $CollectionFile $SCOMExclusionFile |Where-Object {$_.SideIndicator -eq '<='} | ForEach-Object {Write-Host $_.InputObject}

Your help is much appreciated


Powershell Command for Tunnel Type fails when type is IKEv2

$
0
0

Add-VpnConnection -Name "TestVPN" -ServerAddress "pfsense.lumigrow.com" -TunnelType IKEv2 -EncryptionLevel Required -AuthenticationMethod EAP -SplitTunneling $True -AllUserConnection $True

Add-VpnConnectionRoute -ConnectionName "LumigrowVPN" -DestinationPrefix 10.0.0.0/24 -PassThru

Add-VpnConnectionRoute -ConnectionName "LumigrowVPN" -DestinationPrefix 10.0.2.0/24 -PassThru

Add-VpnConnection :  The VPN Connection cannot be added because conflicting PPP Tunnel types are specified. Using L2TP
is recommended. : The parameter is incorrect.
At line:1 char:1
+ Add-VpnConnection -Name "TestVPN" -ServerAddress "pfsense.lumigrow.co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (TunnelType:root/Microsoft/...S_VpnConnection) [Add-VpnConnection], Cim
   Exception
    + FullyQualifiedErrorId : WIN32 87,Add-VpnConnection

But if I select L2TP and then manually go in via the gui and modify to IKEv2 then I am able to use the VPN. 

My issue is I want to be able to script the creation of the VPN connection and not have to intereact with the GUI on each machine.

I can't access information in an xml file...

$
0
0

Hi all,

I'm trying to set a value in an XML file, but Get-Content is erroring with

"Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument".  Error:  :Name cannot begin with the '<' character.

Here's the code that is failing...

$appsets = "C:\temp\appsettings.config"
[xml] $xml =  (Get-Content $appsets)

Here is the contents of the XML file...

<?xml version="1.0" encoding="utf-8"?><appSettings><add key="AppVersion" value="1.0.0.0"</appSettings>

Does anyone know what can be going wrong?

One thing I did notice is that if I copy from the .config file using notepad and past in Insert Code Block I get this...

<?xml version="1.0" encoding="utf-8"?><appSettings><add key="AppVersion" value="1.0.0.0"</appSettings>

Are there hidden line feeds or carriage returns that might be tripping things up?

Any help appreciated...

 

Help with script to disable OWA/Activesync

$
0
0

Hello,

I've written up a script to disable someones mail/activesync in the event an associate is terminated immediately.  Based on the KB articles here:

http://blogs.technet.com/b/messaging_with_communications/archive/2012/06/26/activesync-disabled-accounts-and-devices-continuing-to-sync.aspx

and 

http://blogs.technet.com/b/messaging_with_communications/archive/2012/06/27/part-ii-outlook-amp-owa-disabled-accounts-and-users-still-being-able-to-access.aspx

the script is designed to prompt the admin running it for the username.  It then displays the name of the user for validation.  It then runs through the series of commands to disable their access via OWA/etc.  This part I have down.  It is the next part that I'm a bit iffy on.

There is a possibility that the person may have more than 1 mobile device attached to their account.  This particular line of code is where I'm having trouble with.  Typically when you check someones mobile deviceid attached to their account, it outputs as such: 

APPLd1934j234l23 JALH123hl1dfha12lKdSHaK234.

I'm assuming both entries must be entered into the blocked device property in order to insure their device is blocked out.

#Validates that the end user has a mobile device $VerifyMobile = Get-ActiveSyncDeviceStatistics -Mailbox:"$Username" | Select-Object -ExpandProperty deviceid $DeviceID = Get-ActiveSyncDeviceStatistics –Mailbox "$Username" | Select-Object -ExpandProperty deviceid #If no mobile device is detected, displays that information and exists the script. if ($VerifyMobile -eq $null){ [System.Windows.Forms.MessageBox]::Show("No Mobile Device.","Exiting") exit } #If mobile devices are detected, they are blocked. else { [System.Windows.Forms.MessageBox]::Show("A mobile device has been found and blocked.","Exiting")foreach($entry in $DeviceID){ Set-CASMailbox -Identity "$Username" -ActiveSyncBlockedDeviceIDs "<DeviceID_1>,<DeviceID_2>"

} Set-CASMailbox -Identity "$Username" -ActiveSyncEnabled $false


Full script below.

#The following script is to be used on an associate who's account must be terminated immediately to prevent them from accessing mail on their mobile
#device as well as on OWA/Outlook.


#Imports Active Directory, Exchange Powershell Commandlets and loads a remote powershell session.
Import-Module ActiveDirectory
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
. $env:ExchangeInstallPath\bin\RemoteExchange.ps1
Connect-ExchangeServer -auto

#Declares Variables
$Username = $null
$DeviceID = $null
$UNConfirm = $null
$MobileConfirm = $null
$DisplayName = $null
$DN = $null
$VerifyMobile = $null
$Email = $null
$LogFile = "C:\Scripts\DisableMail+Activesync.txt"

Start-Transcript -Path "C:\Scripts\DisableMail+Activesync.txt"

#Loads Assemblies required for prompts.
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null

#Provides an initial warning of the scripts intentions.
[System.Windows.Forms.MessageBox]::Show("The following script will insure that a user who's account has just been disabled in AD will not be able to use email via webmail or their mobile device.","Disable Access to Mail")

#Loop prompting for username and verfication of username.
do {

$Username = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the associates username:", "Username")
$DisplayName = Get-ADUser -Identity $Username
$DN = $DisplayName.Name

#If propmt is blank, script exists.
if(!$Username)
{
[System.Windows.Forms.MessageBox]::Show("No name entered.  Exiting script.","Blank entry")
exit
}

#Prompts user for validation that the correct person is listed.
$UNConfirm = [System.Windows.Forms.MessageBox]::Show("Is this the correct user? $DN ", "Verify User" , 4)
} until ($UNConfirm -eq "YES" )

#Disables all Mailbox features preventing mail access.
Set-CASMailbox -Identity "$Username" -OwaEnabled $false
Set-CASMailbox -Identity "$Username" -EwsEnabled $false
Set-CASMailbox -Identity "$Username" -EcpEnabled $false
Set-CASMailbox -Identity "$Username" -MapiEnabled $false
Set-CASMailbox -Identity "$Username" -MapiBlockOutlookRpcHttp $true
Set-CASMailbox -Identity "$Username" -EwsAllowMacOutlook $false
Set-CASMailbox -Identity "$Username" -EwsAllowOutlook $false
Set-Mailbox -Identity "$Username" -RecipientLimits 0


#Validates that the end user has a mobile device
$VerifyMobile = Get-ActiveSyncDeviceStatistics -Mailbox:"$Username" | Select-Object -ExpandProperty deviceid
$DeviceID = Get-ActiveSyncDeviceStatistics –Mailbox "$Username" | Select-Object -ExpandProperty deviceid

#If no mobile device is detected, displays that information and exists the script.
if ($VerifyMobile -eq $null){
[System.Windows.Forms.MessageBox]::Show("No Mobile Device.","Exiting")
exit
}

#If mobile devices are detected, they are blocked.
else {
[System.Windows.Forms.MessageBox]::Show("A mobile device has been found and blocked.","Exiting")

foreach($entry in $DeviceID){
Set-CASMailbox -Identity "$Username" -ActiveSyncBlockedDeviceIDs "<DeviceID_1>,<DeviceID_2>"
Set-CASMailbox -Identity "$Username" -ActiveSyncEnabled $false

}



}



#Requests an email address to send a log of the actions to.
$Email = [Microsoft.VisualBasic.Interaction]::InputBox("Enter your email address:", "Send Email with Log")

#Writes to text file the name of the associate who was terminated.
Echo "Username:"
Write-Output $DN >> c:\Scripts\DisableMail+Activesync.txt

#Validates if a mobile device was disabled and in this case if not, writes to output no mobile device was disabled.
if ($VerifyMobile -eq $null){
echo "No mobile device." >> C:\Scripts\DisableMail+Activesync.txt
}

#Writes to output the mobile devices which were disabled.
else{
echo "Mobile Device:"
Write-Output $DeviceID >> C:\Scripts\DisableMail+Activesync.txt
}


Stop-Transcript


Email the log file
$emailFrom = "email@domain.com"
$emailTo = $Email
$subject = "Disable OWA/Activesync for terminated user"
$content = Get-Content $LogFile | ForEach-Object {$_.Split("`r`n")}
$body = [string]::Join("`r`n",$content)
$smtpServer = "mailserver.domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)

Clear-Content C:\Scripts\DisableMail+Activesync.txt


copy lines from large text file for input

$
0
0

hello.  thanks for the time.

i have a large txt file in the sense of having over 10k rows. what i need to do is break it up into multiple files with every 1000 lines.

right now i have this code:

this gets a total of 1000.  the next thing is do the next 1000.. 

Get-Content -totalcount 1000 -path "C:\files\list.txt" > "C:\files\batch1.txt 

I tried this but gave me no results.

Get-Content -totalcount 1000 -path c:\files\list.txt | select-object -skip 1000

and tried it as where the totalcount was 2000 thinking it would skip the first 1000 . no go.

Get-Content -totalcount 2000 -path c:\files\list.txt | select-object -skip 1000


any suggestions?  thanks.

System.Data.Odbc.OdbcException: in Powershell 5 but not in VS2015 running POSHTools

$
0
0

Getting an System.Data.Odbc.OdbcException: when I run a script natively in PowerShell 5 (on Win10 and Server 2k12r2), however if I run the same script in Visual Studio 2015 Enterprise with PowerShell Tools for VS2015 v3.0.323 installed it runs fine and no errors or exceptions.

Any help would be greatly appreciated.

PSVersion                      5.0.10586.63                                                                        
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                             
BuildVersion                   10.0.10586.63                                                                       
CLRVersion                     4.0.30319.42000                                                                     
WSManStackVersion              3.0                                                                                 
PSRemotingProtocolVersion      2.3                                                                                 
SerializationVersion           1.1.0.1

Query I'm running:

$IBIConnection = New-Object System.Data.Odbc.OdbcConnection
            $IBIConnection.ConnectionString = "DSN=iBI DaaS;Uid=myUsername;Pwd=;"

            $IBIOdbcCmd = New-Object system.Data.Odbc.OdbcCommand
 


            $IBIAllSQLQuery = "select [id] as [Feature]
                                    , [[title] as [Description]
                                    , [bugeco.fixed] as [Fixed]
                                from [ES.bugeco]
                                where ([release] like ( '%YYZ' ) or [ES.bugeco].[release_affected] like ( '%YYZ' ) )
                                and [id] in ( 12345, 123456 )
                                order by [id] asc"

            # Init Table
            If ($IBIDataTable -ne $null)
            {
                $IBIDataTable.Clear()
                $IBIDataTable.Dispose()
                Write-Host "Clearing DataTable"
            }
            $IBIDataTable = New-Object system.Data.DataTable "Bug_Table"
            $FeatureCol = New-Object System.Data.DataColumn Feature,([int32])
            $DescriptionCol = New-Object System.Data.DataColumn Description,([string])
            $FixedCol = New-Object System.Data.DataColumn Fixed,([string])
            $IBIDataTable.Columns.Add($FeatureCol)
            $IBIDataTable.Columns.Add($DescriptionCol)
            $IBIDataTable.Columns.Add($FixedCol)

            # Connect to SQL
            $IBIConnection.open()
            $IBIOdbcCmd.CommandText = $IBIAllSQLQuery
            $OdbcAdapter = New-Object system.Data.Odbc.OdbcDataAdapter
            $OdbcAdapter.SelectCommand = $IBIOdbcCmd
            $IBIOdbcCmd.Connection = $IBIConnection

            # Fill Table with SQL Data
            [void]$OdbcAdapter.Fill($IBIDataTable)
            
            # Close SQL Connection
            $IBIConnection.close()

Exception Thrown:

Exception             : System.Management.Automation.MethodInvocationException: Exception calling "Fill" with "1" argument(s): "ERROR [HY000] The request was invalid or the request is without authentication or cannot be otherwise served." --->
                        System.Data.Odbc.OdbcException: ERROR [HY000] The request was invalid or the request is without authentication or cannot be otherwise served.
                           at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
                           at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod)
                           at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader)
                           at System.Data.Odbc.OdbcCommand.ExecuteReader(CommandBehavior behavior)
                           at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
                           at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
                           at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
                           at CallSite.Target(Closure , CallSite , Object , Object )
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : OdbcException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, F:\Workspaces\Visual Studio 2015\Projects\PowerShellProjects\PowerShellProjects\psScripts\HSD_ES Test.ps1: line 55
PipelineIterationInfo : {}
PSMessageDetails      :

Use CSV array to search for and change a registry value

$
0
0

Hi

I am looking into creating a Powershell script that can read a CSV file and search the registry for the value in Column A and if it finds it, change the registry to the value in column b.

For example

In HKCU\Network, search through the drive mappings then based on the example csv data look for the value of RemotePath.  If the value in Oldshare is found, change it to the value in Newshare.

Oldshare, Newshare
\\server1\share1, \\newsrv1\share1
\\server2\share2, \\newsrv1\share2
\\srvxxx01\teamshare, \\newsrv1\teamshare

I have been experimenting with importing the data and then using Set-ItemProperty to change the registry value but I am not experienced enough with Powershell to make make the leap.

Any assistance or advice is greatly received!

Cheers,

Anthony

Newbie help please

$
0
0

Hi

We are rolling out Windows 10 in our environment and I need to find a way to add the current logged on user to the local Administrators group. When we did this with Windows 7 we had a VBScript in the startup folder that would add the current user to the local admin group then delete itself. That script is not working with Windows 10 so rather than trying to make it work I'm asking is there an easier, more efficient way to accomplish this with Powershell?

Thanks so much for any help you can offer

Joshua


Making script ignore all blank spaces on CSV file

$
0
0

Hi,

I am trying to create a script that will change the settings of a large amount of Exchange Online email addresses from a CSV file. However, I get errors from blank spaces on the CSV and I was wondering if there was a way to make it so it just skips over the blank spaces. And also I want it show the syntax of command after I enter it. Can someone please help me out, I actually dont even know what Im doing

Import-Csv $path | Foreach-Object { 
    $EnableLit = [System.Convert]::ToBoolean($_.Lit)
            $EnableClutter =  [System.Convert]::ToBoolean($_.Clutter)
        
            Get-Command Get-WinEvent -Syntax
            Set-Mailbox -Identity $_.EmailAddress -LitigationHoldEnabled $EnableLit -MaxSendSize $_.MaxSendSize -MaxReceiveSize $_.MaxReceiveSize -type $_.type
            Set-Clutter -Identity $_.EmailAddress -Enable $EnableClutter
            Set-MailboxRegionalConfiguration -Identity $_.EmailAddress -Language $_.Language -Timezone $_.Timezone -LocalizeDefaultFolderName:$true     
            Set-MailboxCalendarConfiguration -Identity $_.EmailAddress -WorkingHoursTimeZone $_.WorkingTime
            Enable-Mailbox -Identity $_.EmailAddress -Archive 
}

Creation of Dynamic Distribution List from Powershell

$
0
0

I are Exchange Online. Trying to create a Dynamic Distribution list from powershell with this command

New-DynamicDistributionGroup-Name"Test DDL"-RecipientFilter{(RecipientType -eq 'UserMailbox') -and (CustomAttribute1 -eq 'Permanent') -and (CustomAttribute2 -eq 'Sales Department . Aust') -and (-not(Name -like 'SystemMailbox{*')) -and (-not(Name -like 'CAS_{*')) -and (-not(RecipientTypeDetailsValue -eq 'MailboxPlan')) -and (-not(RecipientTypeDetailsValue -eq 'DiscoveryMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'PublicFolderMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'ArbitrationMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuditLogMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuxAuditLogMailbox'))}

The Dynamic DL is created but when I check the Recipient filter field I see that it is not same as what I used in the powershell command to create the list.For eg I see 'AuxAuditLogMailbox' , 'ArbitrationMailbox' , 'AuditLogMailbox' twice in the Recipient Filter field. However I have entered them only once in the powershell command when I created it.

RecipientFilter           

((((((((((((((((((((((RecipientType -eq 'UserMailbox') -and (CustomAttribute1 -eq 'Perm'))) -and (CustomAttribute2 -eq 'Comm. and Infrastr.Sol Line'))) -and (-not(Name -like 'SystemMailbox{*')))) -and (-not(Name -like 'CAS_{*')))) -and (not(RecipientTypeDetailsValue -eq 'MailboxPlan')))) -and (-not(RecipientTypeDetailsValue -eq 'DiscoveryMailbox')))) -and (-not(RecipientTypeDetailsValue -eq 'PublicFolderMailbox')))) -and (-not(RecipientTypeDetailsValue -eq 'ArbitrationMailbox')))) -and (-not(RecipientTypeDetailsValue -eq 'AuditLogMailbox')))) -and (-not(RecipientTypeDetailsValue -eq 'AuxAuditLogMailbox')))) -and (-not(Name -like 'SystemMailbox{*')) -and (-not(Name -like 'CAS_{*')) -and (-not(RecipientTypeDetailsValue -eq 'MailboxPlan')) -and (-not(RecipientTypeDetailsValue -eq 'DiscoveryMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'PublicFolderMailbox')) -and (-not(RecipientTypeDetailsValue -eq  'ArbitrationMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuditLogMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuxAuditLogMailbox'))) 

Powershell to create Schedule Task on Windows 10

Import file to SQL Server DB

$
0
0

Hello all,

I have a script that writes the following output to a file:

1,1,40,1,1,,2016-02-22
1,1,2,3,1,,2016-02-22
3,1,40,1,1,,2016-02-22
3,1,213,2,1,,2016-02-22
3,1,1771,2,1,,2016-02-22
3,1,2,3,1,,2016-02-22
4,1,40,1,1,,2016-02-22
4,1,191,1,1,,2016-02-22
4,1,516,2,1,,2016-02-22
4,1,2,3,1,,2016-02-22


Now i want to insert all this data at once to a SQL Server database.

Iam using 

$SQL_CONNECTION_STRING="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=database01;Data Source=Serverdb01"


$csvDataTable = Import-CSV -Path "C:\\Supportexport.csv" -Header ID,PARENT,ACL,TYPE,PERMISSION,OWNER,DATE
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $SQL_CONNECTION_STRING
$bulkCopy.DestinationTableName = "[dbo].[FSTABLE]"
$bulkCopy.WriteToServer($csvDataTable)

But iam getting the following error:

Cannot convert argument "rows", with value: "System.Object[]", for "WriteToServer" to type "System.Data.DataRow[]": "Cannot convert the "@{ID=1; PARENT=1; ACL=40; TYPE=1; PERMISSION=1; 
OWNER=; DATE=2016-02-22}" value of type "System.Management.Automation.PSCustomObject" to type "System.Data.DataRow"

Can anyone help me with this?

Regards,

Lostrans

Copy-Item and Variables

$
0
0

I'm pretty new to this, but I'm trying to copy file from Shared Network folder to local folder. It gets the Path and filename ok into the variable, but when using the variable within the cmdlet "Copy-Item", I get an Error.. ???? Why ... What to do ..

Code;

#Find news file of with the extension *.axmodel
$axModelPathAndName = get-childitem $droplocation -recurse | where {$_.extension -eq ".axmodel"} | Sort Name -Descending | Select FullName -First 1 | ft -hidetableheaders
$axModelFileName    = get-childitem $droplocation -recurse | where {$_.extension -eq ".axmodel"} | Sort Name -Descending | Select Name -First 1 | ft -hidetableheaders

write-Infolog ($axModelPathAndName)
write-Infolog ($axModelFileName)
Copy-Item $axModelPathAndName -destination c:\temp -Force

Result;

\\dkxxx01\Build DropZone\DynamicsAX\AX\Ax Build\1.108.1.2\Ax Build 1.108.1.2.axmodel                                                                                         

Ax Build - RSA 1.108.1.2.axmodel                                                                                                                                                                                                            

 - Importing model : Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
Cannot find path 'C:\Windows\system32\Microsoft.PowerShell.Commands.Internal.Format.FormatStartData' because it does not exist.
At line:8 char:14
+     Copy-Item <<<<  $axModelPathAndName -destination c:\temp -Force
    + CategoryInfo          : ObjectNotFound: (C:\Windows\syst...FormatStartData:String) [Copy-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand


Help tidying up the date format

$
0
0

Hi All

I am trying to trim the rubbish from my output for my script but am unable to do so. I have looked up examples for cleaning up the dates but I cant get it to work for my script. Please bear In mind in a new user to PowerShell with a month hands on experience so my script is a little messy.

Here is an example of my output text I would like to trim

I am trying to locate the owner for an AD Group Called '<OU GROUP NAME HERE>', That you are a listed member of. It was created in @{whencreated=02/06/2007 14:33:10}.Can you help me please?

My script for option 13 in my main menu.

13{$GroupName = Read-Host -prompt 'Enter Group Name'
           $Year = Get-ADGroup -identity $GroupName -Properties whencreated | select whencreated
           $UserList = Get-ADGroupMember -identity $GroupName -Recursive | Get-ADObject -Properties Name | Sort-object name | Select Name



                        [int]$GroupMemberM = 0
                        while ( $GroupMemberM -lt 1 -or $GroupMemberM -gt 2 ){
                        Write-Host -ForegroundColor gray "Is the user a Group Member? Yes or No"
                        Write-Host -ForegroundColor green "1. Yes"
                        Write-Host -ForegroundColor red "2. No"
                        $GroupMemberM = read-host "Please Choose an Option"}


                        switch ($GroupMemberM){

                        1{$GroupMemberA = "That you are a listed member of"}
                        2{$GroupMemberA = "You are not listed as a member however, I was given your name as a possible contact"}

                                              }

                        [int]$UserListM = 0
                        while ( $UserListM -lt 1 -or $UserListM -gt 2 ){
                        Write-Host -ForegroundColor gray "Include Group Member Names?"
                        Write-Host -ForegroundColor green "1. Yes"
                        Write-Host -ForegroundColor red "2. No"
                        $UserListM = read-host "Please Choose an Option"}


                        switch ($UserListM){

                        1{$UserListA = "Here is a list of members $UserList"}
                        2{$UserListA = ""}

                                          }

                        "Hi. I am trying to locate the owner for an AD Group Called '$GroupName', $GroupMemberA. It was created in $year.Can you help me please?." | select | clip   #Option 13 is a pre-written script with opt
                        Write-Host -ForegroundColor Gray "Your Script " -nonewline
                        Write-Host -foregroundcolor Green "I am trying to locate the owner for an AD Group Called $GroupName, $GroupMemberA. It was created in $year.Can you help me please? " -nonewline
                        Write-host "has been copied  to the Clipboard"            }

Thanks

powershell dotnet referencing properties

$
0
0

Is there a way in the -property of GROUP-BY commandlet that i can get this to work: 

 $hosts | group -property @{Name=Build;Value=$_.summary.config.product.Build}

Basically trying to get the dotnet property to be the property it sorts by. 

Thanks!


One-liner to show windows firewall rule information and their associated scopes....

$
0
0

Hi! I can get everything except ports and scopes with this powershell one-liner....

Show-NetFirewallRule | where {$_.enabled -eq ‘true’ -AND $_.direction -eq ‘inbound’} |Where-Object {$_.Displayname -like "*Remote*"}

If I add : | Get-NetFirewallAddressFilter I get just the scope and no associated rule names, etc.....like if I ran the command without the pipe to get-netfirewalladdressfilter.

I tried this too, but it still does not show what I need/l || select *, @{n='AddressFilter';e={$_ | Get-NetFirewallAddressFilter}}

Any one-liners to show me what I need?

Check if a cumulative update is installed via powershell script

$
0
0

Hi,

Is there a way to check what cumulative updates are installed in a server using script .. I know i can manually log in and check from the control panel .. but we want to script it out and run it remotely ... 

I tried get-hotfix and also the registry way to get the list but none of them include the CU's list ... 

Thanks

Dheer


-Dheer



DSC - Active Directory User Creation Error "The server cannot handle directory requests"

$
0
0

I've been working on automating an Active Directory installation with Powershell DSC and am having a problem with using the  xADUser resource. I'm using WMF 5.0 Production Preview on Windows Server 2012. I have already installed Active Directory and can add a user through the "Active Directory Users and Computers" manager tool, but when I add a user through DSC with xADUser I get an error saying "Exception calling 'ValidateCredentials' with '2' argument(s): 'The server cannot handle directory requests.'" This is what I have in the configuration block of the script:

xADUser NewUser
{
    DomainName = $Node.FQDN
    DomainAdministratorCredential = $DomainAdminPW
    UserName = $Node.AD_USR_NAME
    Password = $UserPW
    Ensure = 'Present'
    Enabled = $true
}

Any help or ideas would be greatly appreciated.

Cannot pass name of the group by parameter to workflow for get-adgroupmember

$
0
0

Hello.

I have created a workflow in powershell:

workflow send-msg
{
param([string[]] $group, [string[]] $message)
$members = get-adgroupmember -identity $group | select samaccountname
$computers = get-adcomputer -filter * -searchbase "Some OU in AD" | select name

foreach -parallel ($computer in $computers)
{

sequence {
$pc = $computer.name
$owner = Get-WmiObject -Class Win32_ComputerSystem -Property UserName -PSComputerName $pc -ErrorAction silentlycontinue

 if ($owner -ne $null) {
 $username = $owner.Username

  foreach ($member in $members) {
  $user = $member.samaccountname
  $user = "AUSTIN\" + $user

   if ($user -eq $username) {
   $recipient = "/server:" + $pc
   msg * $recipient $message
   }
  }
 }
}
}
}

This row is important:

$members = get-adgroupmember -identity $group | select samaccountname

If I run send-msg -group groupname -message "Something to tell", it ends with error:

Cannot convert 'spravci' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter 'Identity'. U
rčená metoda není podporována.
    + CategoryInfo          : InvalidArgument: (:) [Get-ADGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
    + PSComputerName        : [localhost]

If I change the workflow and write the name of the group inside, for example:

$members = get-adgroupmember -identity spravci | select samaccountname

and I run: send-msg -message "Something to tell"

it runs OK.

Any idea, what do I do wrong?

Thank you

Jan

Learning Powershell and Python

$
0
0

Hi, and Thanks.

First,

I am trying to learn to use the PS, and python programming.  I have Python 2.7 installed in C:\Python27.

I am working in a file C:\Users\...\PythonPrograms.  I am saving my text.py files to C: ...PythonPrograms.  I can run them from from C: ...PythonPrograms using PS > python text.py.  

I want to be able to run them from python, i.e. the '>>>' prompt.  I think the problem is that python doesn't have a path to the text.py file.  How do I fix that?

Second, 

Is there a good book to learn PowerShell?  I do not have much of a background in Computer Science, and I just started using Windows again after a very long absence.  

Thanks, 

George


Viewing all 21975 articles
Browse latest View live


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