Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Is it possible to create a object with multiple class member in powershell?

$
0
0

Hi, guys, 

I'm quite new in powershell scripting. I'm trying to use powershell to analysis some text based log (such as internal network access log).

I saw some object related examples for powershell, for me, it most likely comes from command, not programing.

I'm wondering if I can create a complex object with multi class member in power shell, for example:

Object
|
 ---User
     |
      --- Name
      --- BudgeNo
      --- Department
           |
            ---Manager
                |
                 ---Phone
                 ---Email
           |
            ---hotline
|
 ----Access URL
      |
       ---Good Site
       ---Bad Site

...

So, if I try to check object.access.badsite, and got some finding,  I can just return data like object.user.name/object.user.department.hotline/object.user.manager/object.user.department.manager.phone

...

Is it possible? If so, how could I add a sub-member?

 

Thanks very much for your help and guide in advance.

 


Hide/Show Form Buttons Based on Selection

$
0
0

I am trying to build a simple gui form that has some buttons.  So far the buttons I have created I would like to hide until the tab that they are on is clicked.  Everything is working and this code is still a work in progress.  I would like to keep comments about the code to just the situation about the buttons please.

 

# Functions

## Get Windows Product Key

### Written by Outside Source

function Get-WindowsProductKey([string]$computer)

{

$Reg = [WMIClass] ("\\" + $computer + "\root\default:StdRegProv")

$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\Microsoft\Windows NT\CurrentVersion","DigitalProductId").uvalue)

$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")

$keyStartIndex = [int]52;

$keyEndIndex = [int]($keyStartIndex + 15);

$decodeLength = [int]29

$decodeStringLength = [int]15

$decodedChars = new-object char[] $decodeLength 

$hexPid = new-object System.Collections.ArrayList

for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }

for ( $i = $decodeLength - 1; $i -ge 0; $i--)

    {                

     if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}

     else

       {

        $digitMapIndex = [int]0

        for ($j = $decodeStringLength - 1; $j -ge 0; $j--)

        {

            $byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);

            $hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));

            $digitMapIndex = $byteValue % 24;

            $decodedChars[$i] = $lookup[$digitMapIndex];

         }

        }

     }

$STR = ''     

$decodedChars | % { $str+=$_}

$STR

}

### Start In-House Coding

 

# Start Form Build

Add-Type -AssemblyName System.Windows.Forms

Add-Type -AssemblyName System.Drawing

 

# Form Layout Variables

$form = New-Object system.Windows.Forms.Form # Create Main Form

 

# Main Tab Creation

$tab1 = New-Object System.Windows.Forms.TabPage # Computer Information Tab

$tab2 = New-Object System.Windows.Forms.TabPage # OS Information Tab

$tab3 = New-Object System.Windows.Forms.TabPage # Memory Information Tab

$tab4 = New-Object System.Windows.Forms.TabPage # HDD Information Tab

$tab5 = New-Object System.Windows.Forms.TabPage # Network Information Tab

$tab6 = New-Object System.Windows.Forms.TabPage # Service Information Tab

$tabcontrol = New-Object System.Windows.Forms.TabControl

 

# Form Data Variables

## Output Textbox Variables

$pcoutput = New-Object System.Windows.Forms.TextBox # Computer Information Textbox

$osoutput = New-Object System.Windows.Forms.TextBox # OS Information Textbox

$memoutput = New-Object System.Windows.Forms.TextBox # Memory Information Textbox

$hddoutput = New-Object System.Windows.Forms.TextBox # HDD Information Textbox

$netoutput = New-Object System.Windows.Forms.TextBox # Network Information Textbox

$seroutput = New-Object System.Windows.Forms.RichTextBox # Service Information Textbox

 

## Output Button Variables

$exit = New-Object System.Windows.Forms.Button # Create Exit Button

$aservices = New-Object System.Windows.Forms.Button # Create Get All Services Button

$rservices = New-Object System.Windows.Forms.Button # Create Get Running Services Button

$sservices = New-Object System.Windows.Forms.Button # Create Get Stopped Services Button

 

## Output Label Variables

$authur = New-Object System.Windows.Forms.Label # Create Authur Label

 

## Computer Information

$pc = Get-WmiObject Win32_ComputerSystem # Get Computer Information

$pcmanuf = $pc.Manufacturer

$pcmodel = $pc.Model

$pcuser = $pc.UserName

 

## OS Information

$os = Get-WmiObject Win32_OperatingSystem # Get OS Information

$oscap = $os.Caption

$osarc = $os.OSArchitecture

$osorg = $os.Organization

$osuser = $os.RegisteredUser

$osname = $os.CSName

 

## Regular Variables

$pkey = Get-WindowsProductKey . # Get OS Product Key

$license = Get-WmiObject -query "Select * from SoftwareLicensingProduct Where LicenseStatus = 1" # Get All License Information  With Status of 1

$memory = Get-WmiObject Win32_PhysicalMemory # Get Physical Memory Information

$memarray = Get-WmiObject Win32_PhysicalMemoryArray # Get Overall Physical Memory Information

$drives = Get-WmiObject -query "Select * from Win32_LogicalDisk Where DriveType = 3" # Get All Local HDDs

$netadapterconfig = Get-WmiObject -query "Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True" # Get All Network Adapter Information

$services = Get-WmiObject Win32_Service | sort DisplayName | select-object SystemName,DisplayName,StartMode,State,PathName # Get All Registered Services

$tbsize = New-Object System.Drawing.Size(725,400) # Textbox Size

$break = "==================================`r`n" # Line Break

$tbbcolor = "White" # Textbox Background Color

 

# Variables for Math

$bytes = "1073741824"

$bytes6 = "1000000" # Bytes 10^6

$kb = "1048576"

$mb = "1024"

 

# Convert Install Date to Something Readable

$instally = $os.InstallDate.Substring(0,4) # Get Year

$installm = $os.InstallDate.Substring(4,2) # Get Month

$installd = $os.InstallDate.Substring(6,2) # Get Day

$installh = $os.InstallDate.Substring(8,2) # Get Hours

$installmm = $os.InstallDate.Substring(10,2) # Get Minutes

$installs = $os.InstallDate.Substring(12,2) # Get Seconds

$install = "$installm/$installd/$instally $installh`:$installmm`:$installs" # Create Readable Date/Time Stamp

 

# Convert Last Reboot to Something Readable

$rebooty = $os.LastBootUpTime.Substring(0,4) # Get Year

$rebootm = $os.LastBootUpTime.Substring(4,2) # Get Month

$rebootd = $os.LastBootUpTime.Substring(6,2) # Get Day

$rebooth = $os.LastBootUpTime.Substring(8,2) # Get Hours

$rebootmm = $os.LastBootUpTime.Substring(10,2) # Get Minutes

$reboots = $os.LastBootUpTime.Substring(12,2) # Get Seconds

$reboot = "$rebootm/$rebootd/$rebooty $rebooth`:$rebootmm`:$reboots" # Create Readable Date/Time Stamp

 

# Size Conversions

$maxcapacity = $memarray.MaxCapacity / $memory.Count # Get memory max capacity and devide it by the number of slots

$maxcapacity = $maxcapacity / $kb # Convert memory max capacity to MB

 

# Get License Status

foreach($status in $license) {

 if($status.LicenseStatus -eq 1) {

$lstatus = "Product Licensed Properly"

}

else {

$lstatus = "Product Not Licensed Properly"

}

}

 

# Button Functions

## Exit Button

$exit_OnClick = {

$form.Close() # Close Form

}

 

## Services Buttons

### Get All Services

$aservices_OnClick = {

$aservices = Get-WmiObject Win32_Service | sort DisplayName | select-object SystemName,DisplayName,StartMode,State,PathName # Get All Registered Services

$seroutput.Clear()

foreach($aservice in $aservices) {

$sername = $aservice.DisplayName

$sermode = $aservice.StartMode

$serstate = $aservice.State

$seroutput.Text += "Service Name: $sername`r`n"

$seroutput.Text += "Service Start Mode: $sermode`r`n"

$seroutput.Text += "Service State:  $serstate`r`n"

$seroutput.Text += "-------------------------------`r`n"

}

}

 

### Get Running Services

$rservices_OnClick = {

$rservices = Get-WmiObject Win32_Service -Filter "State = 'Running'" | sort DisplayName

$seroutput.Clear()

foreach($rservice in $rservices) {

$sername = $rservice.DisplayName

$sermode = $rservice.StartMode

$serstate = $rservice.State

$seroutput.Text += "Service Name: $sername`r`n"

$seroutput.Text += "Service Start Mode: $sermode`r`n"

$seroutput.Text += "Service State:  $serstate`r`n"

$seroutput.Text += "-------------------------------`r`n"

}

}

 

### Get Stopped Services

$sservices_OnClick = {

$sservices = Get-WmiObject Win32_Service -Filter "State = 'Stopped'" | sort DisplayName

$seroutput.Clear()

foreach($sservice in $sservices) {

$sername = $sservice.DisplayName

$sermode = $sservice.StartMode

$serstate = $sservice.State

$seroutput.Text += "Service Name: $sername`r`n"

$seroutput.Text += "Service Start Mode: $sermode`r`n"

$seroutput.Text += "Service State:  $serstate`r`n"

$seroutput.Text += "-------------------------------`r`n"

}

}

 

# Form Layout

$form.Text = "Computer Information v0.2b" # Form Title

$form.AutoSize = $True # Turn on AutoSize

$form.AutoSizeMode = "GrowandShrink" # AutoSize Will Grow and Shrink Overall Form

 

# Tab 1 Data

$tab1.Text = "Computer Information" # Tab 1 Title

$tab1.Name = "TabPage1"

$tab1.TabIndex = 0 # Index Value

 

## Tab 1 Output

$pcoutput.MultiLine = $True # Create Textbox

$pcoutput.Size = $tbsize # Textbox Size 

$pcoutput.ScrollBars = "Vertical" # Vertical Scrollbars

$pcoutput.Text = "Computer Information`r`n$break"

$pcoutput.Text += "Manufacturer: $pcmanuf`r`n" # PC Manufacturer

$pcoutput.Text += "Model: $pcmodel" # PC Model

 

$pcoutput.ReadOnly = $True # Textbox Ready-Only

$pcoutput.BackColor = "$tbbcolor" # Textbox Background Color

 

$tab1.Controls.Add($pcoutput) # Create Total Tab Output

 

# Tab 2 Data

$tab2.Text = "OS Information" # Tab 2 Title

$tab2.Name = "TabPage2"

$tab2.TabIndex = 1 # Index Value

 

# Tab 2 Output

$osoutput.MultiLine = $True # Create Textbox

$osoutput.Size = $tbsize # Textbox Size

$osoutput.ScrollBars = "Vertical" # Vertical Scrollbars

$osoutput.Text = "OS Information`r`n$break"

$osoutput.Text += "Operating System: $oscap $osarc`r`n" # Operating System and Architechure

$osoutput.Text += "Product Key: $pkey`r`n" # OS Product Key

$osoutput.Text += "License Status: $lstatus`r`n" # OS License Status

$osoutput.Text += "Install Date: $install`r`n" # OS Install Date

$osoutput.Text += "Last Reboot: $reboot`r`n" # OS Last Reboot

$osoutput.Text += "Organization: $osorg`r`n" # Registered Organizaton

$osoutput.Text += "Registered Owner: $osuser`r`n" # Registered User

$osoutput.Text += "Computer Name: $osname`r`n" # Current Computer Name

$osoutput.Text += "Current User: $pcuser" # Current User Number

 

$osoutput.ReadOnly = $True # Textbox Read-Only

$osoutput.BackColor = "$tbbcolor" # Textbox Background Color

 

$tab2.Controls.Add($osoutput) # Create Total Tab Output

 

# Tab 3 Data

$tab3.Text = "Memory Information" # Tab 3 Title

$tab3.Name = "TabPage3"

$tab3.TabIndex = 2 # Index Value

 

# Tab 3 Output

$memoutput.MultiLine = $True # Create Textbox

$memoutput.Size = $tbsize # Textbox Size

$memoutput.ScrollBars = "Vertical" # Vertical Scrollbars

$memoutput.Text = "Memory Information`r`n$break"

foreach($stick in $memory) { # Get Each Memory Module

# Convert Capacity

$capacity = $stick.Capacity / $bytes # Total Stick capacity converted to GB

$membank = $stick.DeviceLocator # Determine Which Slot Module is In

$memmanu = $stick.Manufacturer # Get Module Manafacturer

$mempn = $stick.PartNumber # Get Module Part Number

$memsn = $stick.SerialNumber # Get Module Serial Number

$memoutput.Text += "Location: $membank`r`n"

$memoutput.Text += "Manufacturer: $memmanu`r`n"

$memoutput.Text += "Part Number: $mempn`r`n"

$memoutput.Text += "Serial Number $memsn`r`n"

$memoutput.Text += "Capacity: $capacity GB`r`n"

$memoutput.Text += "Max Capacity: $maxcapacity GB`r`n"

$memoutput.Text += "-------------------------------`r`n"

}

 

$memoutput.ReadOnly = $True # Textbox Read-Only

$memoutput.BackColor = "$tbbcolor" # Textbox Background Color

 

$tab3.Controls.Add($memoutput)  # Create Total Tab Output

 

# Tab 4 Data

$tab4.Text = "Hard Drive Information" # Tab 4 Title

$tab4.Name = "TabPage4"

$tab4.TabIndex = 3 # Index Value

 

# Tab 4 Output

$hddoutput.MultiLine = $True # Create Textbox

$hddoutput.Size = $tbsize # Textbox Size

$hddoutput.ScrollBars = "Vertical" # Vertical Scrollbars

$hddoutput.Text = "Hard Drive Information`r`n$break"

foreach($drive in $drives) {

$deviceid = $drive.DeviceID # HDD Letter

$size = $drive.Size / $bytes # HDD Max Size

$fspace = $drive.FreeSpace / $bytes # HDD Free Space

$uspace = $size - $fspace # Calculate HDD Used Space

$size = [System.Math]::round($size, 2) # Rounds Decimal Places

$fspace = [System.Math]::round($fspace, 2) # Rounds Decimal Places

$uspace = [System.Math]::round($uspace, 2) # Rounds Decimal Places

if($size -eq 0) {

# Filter out results with HDD Max Size of 0

""

}

else {

# Console Output

$hddoutput.Text += "Drive: $deviceid`r`n" # Get Drive Letter

$hddoutput.Text += "Total HDD Size: $size GB`r`n" # Get HDD Total Size

$hddoutput.Text += "Total HDD Free Space: $fspace GB`r`n" # Get HDD Free Space

$hddoutput.Text += "Total HDD Used Space: $uspace GB`r`n" # Get HDD Used Space

}

}

 

$hddoutput.ReadOnly = $True

$hddoutput.BackColor = "$tbbcolor"

 

$tab4.Controls.Add($hddoutput)

 

# Tab 5 Data

$tab5.Text = "Network Information"

$tab5.Name = "TabPage5"

$tab5.TabIndex = 4

 

# Tab 5 Output

$netoutput.MultiLine = $True

$netoutput.Size = $tbsize # Textbox Size

$netoutput.ScrollBars = "Vertical"

$netoutput.Text = "Network Adapter Information`r`n$break"

foreach($adapter in $netadapterconfig) {

# Console Output

$netdesc = $adapter.Description

$netipv4 = $adapter.IPAddress[0]

$netsub = $adapter.IPSubnet[0]

$netgate = $adapter.DefaultIPGateway

$netmac = $adapter.MACAddress

$netoutput.Text += "Name: $netdesc`r`n" # Get Network Adapter Name

$netoutput.Text += "IP Address: $netipv4`r`n" # Get IPv4 Address

$netoutput.Text += "Subnet Mask: $netsub`r`n" # Get Subnet

$netoutput.Text += "Gateway: $netgate`r`n" # Get Gateway

$netoutput.Text += "MAC: $netmac`r`n"# Get Mac Address

$netoutput.Text += "-------------------------------`r`n"

}

 

$netoutput.ReadOnly = $True

$netoutput.BackColor = "$tbbcolor"

 

$tab5.Controls.Add($netoutput)

 

# Tab 6 Data

$tab6.Text = "Services Information"

$tab6.Name = "TabPage6"

$tab6.TabIndex = 5

 

# Tab 6 Output

$seroutput.MultiLine = $True

$seroutput.Size = $tbsize # Textbox Size

$seroutput.ScrollBars = "Vertical"

$seroutput.Text = "Services Information`r`n$break"

foreach($service in $services) {

$sername = $service.DisplayName

$sermode = $service.StartMode

$serstate = $service.State

$seroutput.Text += "Service Name: $sername`r`n"

$seroutput.Text += "Service Start Mode: $sermode`r`n"

$seroutput.Text += "Service State:  $serstate`r`n"

$seroutput.Text += "-------------------------------`r`n"

}

$seroutput.ReadOnly = $True

$seroutput.BackColor = "$tbbcolor"

 

$tab6.Controls.Add($seroutput)

 

# Tab Creation

$tabcontrol.Size = New-Object System.Drawing.Size(750,440)

$tabcontrol.Controls.Add($tab1)

$tabcontrol.Controls.Add($tab2)

$tabcontrol.Controls.Add($tab3)

$tabcontrol.Controls.Add($tab4)

$tabcontrol.Controls.Add($tab5)

$tabcontrol.Controls.Add($tab6)

$tabcontrol.SelectedIndex = 0

 

# Create All Services Button

$aservices.Name = "AllServices"

$aservices.Text = "All Services"

$aservices.Location = New-Object System.Drawing.Size(5,450)

$aservices.Width = 100

$aservices.add_Click($aservices_OnClick)

 

# Create Running Services Button

$rservices.Name = "RunningServices"

$rservices.Text = "Running Services"

$rservices.Location = New-Object System.Drawing.Size(105,450)

$rservices.Width = 100

$rservices.add_Click($rservices_OnClick)

 

# Create Stopped Services Button

$sservices.Name = "StoppedServices"

$sservices.Text = "Stopped Services"

$sservices.Location = New-Object System.Drawing.Size(205,450)

$sservices.Width = 100

$sservices.add_Click($sservices_OnClick)

 

# Exit Button Creation

$exit.Name = "Exit"

$exit.Text = "Exit"

$exit.Location = New-Object System.Drawing.Size(675,500)

$exit.add_Click($exit_OnClick)

 

# Authur Label Creation

$authur.Text = "Written By: Joseph Monarch"

$authur.AutoSize = $True

$authur.Location = New-Object System.Drawing.Size(5,500)

 

# Add All Controls

$form.Controls.Add($tabcontrol)

$form.Controls.Add($aservices)

$form.Controls.Add($rservices)

$form.Controls.Add($sservices)

$form.Controls.Add($authur)

$form.Controls.Add($exit)

 

# Create Form

$form.ShowDialog() | Out-Null

 

$aservices, $rservices and $sservices are the buttons I would like to hide until the Services Tab is clicked.

I have tried several things with no avail.  Any help is much appreciated.

powershell only showing last line output

$
0
0

Hi Team,

I'm checking the multiple server performance output. But the export csv output only showing last server performance details. Could you please verify below script  and share the valuable information how to fix this issue.

When using the Append command script not generating any output file


$Servers= import-csv "C:\testcounter.csv"
ForEach($Server in $Servers)
{
$ObjectName=$Server.ObjectName
$CounterName=$Server.CounterName
$InstanceName=$Server.InstanceName
$Server=$Server.Server
$Result=Get-Counter -Counter "\\$server\$ObjectName($InstanceName)\$CounterName"

    $CounterSamples = $Result | % {$_.CounterSamples}

    $MasterArray = @()
 
    ForEach($CounterSample in $CounterSamples)
    {
        $TempArray = @()
        $TempArray = "" | Select Server, ObjectName, CounterName, InstanceName, SampleValue, DateTime

        $Split = $CounterSample.Path.Remove(0,2)
        $Split = $Split.Split("\")

        $TempArray.Server = $Split[0]
        $TempArray.ObjectName = $Split[1].Split("(")[0]
        $TempArray.CounterName = $Split[2]
        $TempArray.InstanceName = $CounterSample.InstanceName
        $TempArray.SampleValue = $CounterSample.CookedValue
        $TempArray.DateTime = $CounterSample.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")

        $MasterArray+= $TempArray

  }

}
$MasterArray | Export-Csv test.csv

Security Log

$
0
0

I'm trying to get information from a security log.  This is what I have so far:

$EDate = Get-EventLog -LogName Security -InstanceId 4732 -Newest 1 -computername $PC | select-object timegenerated

This gives me the data I need, but when I export this data in .csv this is a sample of the output I get:

@{TimeGenerated=11/24/2014 8:45:26 AM}

Is there a way I can just get the date and time without the "@{TimeGenerated=" ???

I've tried using {$_.Split("`n")[1].Trim().replace("@{TimeGenerated","")} but haven't had any luck on getting commands like this to work. 

If test condition result to csv file

$
0
0

Hi Team,

Below are the few lines of my script, Could any one tell me how to export the If-condition test result  of this script to a csv file

$Servers= import-csv "C:\testcounter.csv"
$MasterArray = @()
ForEach($Server in $Servers)
{
$ObjectName=$Server.ObjectName
$CounterName=$Server.CounterName
$InstanceName=$Server.InstanceName
$Server=$Server.Server
If(Test-Connection -quiet -computer $server)
{
$Result=Get-Counter -Counter "\\$server\$ObjectName($InstanceName)\$CounterName"
}

 

New-mailboxexportrequest to export contacts folder to CSV file

$
0
0

Hello,

I'm having trouble exporting out the contacts to a .csv file. I have a UNC share created with the Exchange trusted subsystem with full control on the share and the ntfs permissions. I can do the export to .pst but I need it in csv format and am not sure how to first convert to string and then export the file to csv.

Help appreciated. Thank you

Gordon

BITS-Transfer with IIS server.

$
0
0

I m tying to upload and download files from IIS server using BITS-Tansfer commandlets. my BITS jobs are getting queued but they are not completing even after explicitly resuming them.


I have configured IIS ,where i have enabled BITS-IIS server extention for client upload.

tried downloading file from server with powershell commandlet as

Start-BitsTransfer -Asynchronous -Priority High -TransferType Download -Source http://myweb/vdir/validity.txt -Destination C:\ -Authentication Basic -Credential SERVER12\Administrator -ProxyBypass 169.254.71.160:80 -ProxyUsage Override -ProxyList 169.254.71.160:80

Both upload and download are not working. when i opened this IIs website from another computer from same domain and tried download files there using BITS, it shows jobstatus "Transferred"...bt it is not downloading data...atleast i m not able to see the data in destination i have given. 

 

How to easily create log files

$
0
0

Hi Mr.Experts,

I need the script to create a log file that will show the whole process and errors if occurred.

how do I do this ? Please find the below script.

 

$Servers= import-csv "C:\testcounter.csv"
$MasterArray = @()
ForEach($Server in $Servers)
{
$ObjectName=$Server.ObjectName
$CounterName=$Server.CounterName
$InstanceName=$Server.InstanceName
$Server=$Server.Server
$connected = Test-Connection $server -count 1 -quiet
If($connected)
{
$server,$connected | Out-File C:\Connected_server.txt
$Result=Get-Counter -Counter "\\$server\$ObjectName($InstanceName)\$CounterName"

$CounterSamples = $Result | % {$_.CounterSamples}

#Splitting the get-counter output to the desired format

ForEach($CounterSample in $CounterSamples)
{
$TempArray = @()
$TempArray = "" | Select Server, ObjectName, CounterName, InstanceName, SampleValue, DateTime

$Split = $CounterSample.Path.Remove(0,2)
$Split = $Split.Split("\")

$TempArray.Server = $Split[0]
$TempArray.ObjectName = $Split[1].Split("(")[0]
$TempArray.CounterName = $Split[2]
$TempArray.InstanceName = $CounterSample.InstanceName
$TempArray.SampleValue = $CounterSample.CookedValue
$TempArray.DateTime = $CounterSample.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")

$MasterArray+= $TempArray

}
}
else
{
$server,$connected | Out-File C:\NotConnected_Server.txt
}
}
$MasterArray | Export-Csv Performance_All.csv -Notype
}


Found the AD Group and members and exported to a csv but require the managedby users email address

$
0
0

Hi

I have been tasked with obtaining all our Active Directory OU's that allow users access to our shared drives. These OU's have a user in the managedby field.

Im very new to Powershell so please bear with my coding which I did below. It does a job for me but please point out if I have done anything wrong or I could do better.

There are 2 things that I would like to add

1 - Get the script to loop through all OU's rather than name them at the top individually eg Shared Admin

2 - Use the Managedby email of the person who looks after the OU

 

*********************************************

Import-Module ActiveDirectory -Force

"Shared Admin" |

foreach {

 $group = Get-ADGroup -Identity $_ -Properties ManagedBy

 

Get-ADGroupMember -Identity $_ |

 select @{N='GroupName'; E={$group.Name}},

 @{N='ManagedBy'; E={$group.ManagedBY}},

 Name, samAccountName | 

 Export-Csv -NoTypeInformation -Path  "$($group.Name).csv"

 }

 

$file += "c:\AD\$($group.Name).csv"

 

Send-MailMessage -smtpServer emailserver.domain.local -to "Me <me@domain.co.uk>", "You <you@domain.co.uk>" -from "Admin <admin@domain.co.uk>" -subject "Shared Drive Information for $($group.Name)" -Attachments $file -body "Hi. 

 

The attchment below shows you all the people who have access to the share you look after $($group.Name)

 

Regards

 

Server Admin Team"

*****************************************

 

Thanks in Advance

 

Martyn

Take Charge of Environment Variables in PowerShell

$
0
0

Environment variables contain important pieces of information about the system. For example, the SystemRoot environment variable tells you the Windows OS installation path (e.g., C:\Windows) and the Path environment variable lists the directories that Windows will search for executable programs and DLL files. 

Read More

Do not see what I expect using get-childitem

$
0
0

Hi All,  New to PowerShell and still learning BIG TIME!  Big Smile

Playing with Get-PSDrive... I do set-location hklm:  browse to the registry key - HKLM\Software\Microsoft\OLE - and then do a get-childitem ... my question is this:
When I do get-childitem I see all of the "folders" under the above KEY but not the "local" entries that are directly in that key.  I was researching an error I am seeing  (RPC Server unavailable) and it asks  that we modify - value: EnableDCOM
If I open REGEDIT I see that value, but thought I would use PowerShell to do this work and find it strange that while I can see AppCompat, Eventlog, Extensions "Folders".....  I do not see the value EndableDCOM.. Should I be using something other than get-childitem?

Getting web server information through WMI

$
0
0

Specifically, what I want to do is determine the value of SSLFlags, especially SSLRequireCert.

 

On servers which have an applicationhost.config file at \\server\admin$\system32\inetsrv\config, I can access it using something like:

 

[xml]$config=gc  \\server\admin$\system32\inetsrv\config\applicationhost.config

 

$config.configuration."system.webserver".security.access

 

or

 

$config.configuration.location[1]."system.webserver".security.access

 

I haven't figured out how to change the value in brackets to identify each site.

 

When I try to access information via WMI, it will work if I'm logged into the server, but not remotely.  When trying to do it remotely, I get an access denied.  If PSRemoting is the only answer, I may be out of luck because of network policies here.

 

Thanks,

 

J

Question regarding variable

$
0
0

I'm parsing a list of machines to get a list of profiles, and a list of admin shares.

If I check individually, it works.  If I call the functions I created, in the same pass, only the first returns info.

For instance:

Function Get-Shares
{
 param($box)
 $shares=gwmi win32_share -computername $box -erroraction silentlycontinue|?{$_.path -like "*\"}|Select @{n="FullPath";e={"\\{0}\{1}" -f $_.pscomputername,$_.name}}
 "Shares:"
 $shares
}

Function Get-Profiles
{
param($box)
 $reg=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$box)
 $regkey=$reg.opensubkey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList")
 $profiledir=$regkey.getvalue("profilesdirectory")
 $profilepath="\\$box\$profiledir" -replace ":","$"
 $profiles=gci $profilepath -Exclude "Public"|?{$_.psiscontainer}|%{$_.fullname}|%{get-item "$_\ntuser.dat" -force}|select fullname
 "Profiles:"
 $profiles
}


Foreach ($box in gc .\online.txt)
{
 Get-Shares $box
 Get-Profiles $box
{

will list the shares, but not profiles.  And vice-versa if reversed.

If I set $box to one of the machine names and type Get-Shares $box (or just enter the machine name), it works.  Similarly, the same happens with Get-Profiles $box/machine name.

Any idea why this might happen?  It's kind of puzzling.

WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

$
0
0

I am trying to run this function to the runt he following function to enable the agents in bamboo

function Enable-Agent([array]$agents){

    $agents | %{

        write-host "enabling agent name: $_"

        $id = Get-AgentId $_

        write-host "agent id: $id"

        $enableAgentUrl = $bambooServer + "/admin/agent/enableAgent.action?agentId=" + $id + "&" + $bambooAuthentication

        $html = Invoke-WebRequest $enableAgentUrl

    }

}

 

I get the following error: 

 

Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.

At C:\SVN_Working\development\projects\infrastructure\bamboo\trunk\common\power

shell\bambooAgentFunctions.ps1:118 char:17

    + $html = Invoke-WebRequest $enableAgentUrl

    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException

    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

 

This works fine for one of my teammates. Just errors out for me. Am I missing any setting here? I am very new to Powershell. Appreciate any help here. Thanks,

Get-Service Command

$
0
0

I am writing a script that will monitor 5 services on a Windows 2008 server.   I was told by our server tech that sometimes that one of these five services can be "hung" yet in services.msc still show as "running".   So I did a get-help get-service -examples and under example 8 it says the following.

This command shows that when you sort services in ascending order by the value of their Status property, stopped services appear before running services. This happens because the value of Status is an enumeration, in which "Stopped" has a value of "1", and "Running" has a value of 4.

I have this in my script:   $result1 = (Get-Service "ILEDataInterfaceLayer" -ComputerName $Server).status   $result1 will contain "Running" or "Stopped" but how do I capture the "1" or "4" they speak of in the help example?

 


WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

$
0
0

I am trying to run this function to enable the agents in bamboo

function Enable-Agent([array]$agents){

    $agents | %{

        write-host "enabling agent name: $_"

        $id = Get-AgentId $_

        write-host "agent id: $id"

        $enableAgentUrl = $bambooServer + "/admin/agent/enableAgent.action?agentId=" + $id + "&" + $bambooAuthentication

        $html = Invoke-WebRequest $enableAgentUrl

    }

}

 

I get the following error: 

 

Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.

At C:\SVN_Working\development\projects\infrastructure\bamboo\trunk\common\power

shell\bambooAgentFunctions.ps1:118 char:17

    + $html = Invoke-WebRequest $enableAgentUrl

    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException

    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

 

This works fine for one of my teammates. Just errors out for me. Am I missing any setting here? I am very new to Powershell. Appreciate any help here. Thanks,

Help with parsing information into the file name

$
0
0

Using this:

$site = Get-SPSite "http://contoso.comsites/Todd"

I am able to get this:

Title                                                                                                      

-----                                                                                                      

Todd       

I want to just take the "Todd"  and use it in the filename when outputting to CSV.

 

This is my script:

 #Add the SharePoint Powershell SnapIn

 Add-PSSnapin microsoft.sharepoint.powershell -EA 0 

 #Edit the URL below for the specific site collection you wish to extract alerts from

 $site = Get-SPSite "http://contoso.rjf.com/sites/Todd"

 $TitleString = Get-SPSite $site | Get-SPWeb -Limit All | Select Title 

 $alertResultsCollection = @()   

 foreach ($web in $site.AllWebs) {     

 foreach ($alert in $web.Alerts){   

 $alertURL = $web.URL + "/" + $alert.ListUrl   

 $alertResult = New-Object PSObject   

 $alertResult | Add-Member -type NoteProperty -name "List URL"        -value $alertURL  

 $alertResult | Add-Member -type NoteProperty -name "Alert Title"        -value $alert.Title 

 $alertResult | Add-Member -type NoteProperty -name "Alert Type"       -value $alert.AlertType 

 $alertResult | Add-Member -type NoteProperty -name "Subscribed User"       -value $alert.User  

 $alertResultsCollection += $alertResult  

  }  

   } 

   $site.Dispose()  

   $alertResultsCollection  

$Path = "F:\"

$Prefix = $TitleString

$Suffix = "_SiteAlerts"

$FileExt = ".csv"

 

 ## Export to CSV  

 $alertResultsCollection | Export-CSV ($path + $Prefix + $Suffix + $FileExt) 

 

What this does is give me a filename as "@{Title=Todd}_SiteAlerts.csv"

How do I get it to just give me Todd_SiteAlerts.csv?
PS.....not a big fan of  the $path + $Prefix + $Suffx + $FileExt either. 

Import Variable

$
0
0

Hi,

How do I get $.name to be working on the script that refer to the same variable.
$_.name only working the first condition checking.

Import-Csv .\DG.csv | ForEach {
if (get-distributiongroup $_.name){
Add-DistributionGroupMember -Identity $_.name -member $_.EmailAddress
}
else{
New-DistributionGroup -Name $._name -OrganizationalUnit "Contoso.com/Groups" -PrimarySmtpAddress $_.PrimarySmtpAddress -Type "Distribution" -MemberDepartRestriction Closed
Add-DistributionGroupMember -Identity $_.name -member $_.EmailAddress
}
}

Different result with $_.LastWriteTime

$
0
0

Hi,

I have a folder with 180 000 small files and want to run the following command

$LastTotal = Get-Childitem -Path C:\utdelat\2\Archived\* | where-object { $_.LastWriteTime -lt (get-date).AddDays(-63) } 

Write-host "$($LastTotal.count)"

The result comes differently each time i run it.
First time i run it, i got 887, second time 890
am i doing wrong something here?
Please help, thanks :-)

Uncheck the attribute "deny this user permission to log on to remote session host server in AD

$
0
0

Hello, I am new to powershell and mostly get my scripts by hunting down different links and piecing together what I want. I just received an excel sheet of bulk userIDs where I have to uncheck the option:

"deny this user permission to log on to remote session host server" to enable RDP for them. 

I am at the basic level so I understand set-aduser, Please help.

 

Viewing all 6937 articles
Browse latest View live