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

Append Text to Description Field

$
0
0

Hello,

I have a script that I am using to take a list of computer objects, update the description, disable the ADaccount, and move the adobject to another OU.  This script works perfectly in my lab.  I would like to be able to append to the current description, rather than overwriting it.  Here is what I am using for the Set-ADaccount line:

Set-ADComputer $ADComputer -Description "$($_.Description) - Computer Disabled on $(Get-Date)" -Enabled $false

Unfortunately, this still just overwrites the Description field.  What should I do differently in order to append to the field?  For example:  "Sharepoint Server - Computer Disabled on 7/16/2014"

Thank you in advance!

Regards,
BrianSW 


List user shared file permission

$
0
0

Hi,

 

Using below script i am able to get the shared folder permission including  windows default share( ADMIN$, C$ etc).

Can you please help me how to exclude default share in below script?

 

Function Get-NtfsRights($name,$path,$comp)

{

$path = [regex]::Escape($path)

$share = "\\$comp\$name"

$wmi = gwmi Win32_LogicalFileSecuritySetting -filter "path='$path'" -ComputerName $comp

$wmi.GetSecurityDescriptor().Descriptor.DACL | where {$_.AccessMask -as [Security.AccessControl.FileSystemRights]} |select `

@{name="Principal";Expression={"{0}\{1}" -f $_.Trustee.Domain,$_.Trustee.name}},

@{name="Rights";Expression={[Security.AccessControl.FileSystemRights] $_.AccessMask }},

@{name="AceFlags";Expression={[Security.AccessControl.AceFlags] $_.AceFlags }},

@{name="AceType";Expression={[Security.AccessControl.AceType] $_.AceType }},

@{name="ShareName";Expression={$share}}

}

Get-NtfsRights

 

 

gc d:\monitor\serverlist.txt | foreach {

if ($shares = Get-WmiObject Win32_Share -ComputerName $_ | Where {$_.Path})

{

$shares | Foreach { Write-Progress -Status "Get share information on $($_.__Server)" $_.Name

Get-NtfsRights $_.Name $_.Path $_.__Server}

}

else {"Failed to get share information from {0}." -f $($_.ToUpper())}

} | ft Principal,Rights,AceFlags,AceType -GroupBy ShareName -Wrap | Out-File result.txt

 

Import from CSV, set Dial in Tab and ad to user

$
0
0

Hi All

I'm going to aplogise in advance for this - its been many years since I've done any coding so am doing a crash-course in Powershell - it will be evident in what I post!

I am struggling with setting the Dial In tab to active when doing a bulk import from a csv file.  I suspect my syntax is wrong, but I've been looking at it so long that I can't see my error.

I would prefer not to use Quest as I want this to be fairly portable, but so far I can't find a way around it.

Any help very much appreciated. 

 

=========

Import-Module ActiveDirectory
Add-PSSnapin Quest.ActiveRoles.ADManagement
$Users = Import-Csv -Delimiter ";" -Path ".\userslist.csv"
foreach ($User in $Users)
{
    $OU = "OU=Test, DC=test,DC=test,DC=test"
    $password = ConvertTo-SecureString -AsPlainText "Test0nly" -Force
    $Detailedname = $User.firstname + $User.name
    $SAM = $User.Firstname + $User.name
    
    New-ADUser -Name $Detailedname -SamAccountName $SAM -UserPrincipalName ($SAM + '@test') -DisplayName $Detailedname -GivenName $user.firstname -Surname $user.name -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path $OU  

# Modify remote access permissions for all users in "example" OU

Get-QADUser -SearchBase 'OU=Test, DC=test,DC=test,DC=test' -Filter * -SizeLimit 0
Set-QADUser -ObjectAttributes @{msNPAllowDialin=$true}|
% { Add-ADGroupMember 'radius' -Members $_ }
}

===========================

error message is

cmdlet Set-QADUser at command pipeline position 1
Supply values for the following parameters:
Identity: Get-QA
Set-QADUser : Cannot resolve directory object for the given identity: 'Get-QA'.
At line:10 char:12
+ Set-QADUser <<<<  -ObjectAttributes @{msNPAllowDialin=$true}|
    + CategoryInfo          : NotSpecified: (:) [Set-QADUser], ObjectNotFoundException
    + FullyQualifiedErrorId : Quest.ActiveRoles.ArsPowerShellSnapIn.DirectoryAccess.ObjectNotFoundException,Quest.Acti
   veRoles.ArsPowerShellSnapIn.Powershell.Cmdlets.SetUserCmdlet

 

Copy folders and subfolders to another destination

$
0
0

Hi,

I am trying attached script but it doesn’t work well. Everything is OK except line with Robocopy.

I don’t know what parameters I should use.

I need copy newest file from each folder and subfolders to destinations with the same folder name on another dsic.

I have no idea how to use robocopy in the right way. I don't know where I make a mistake.

I have spent many hours but without effect.

Excuse my bad English, please.

Thank you for your helpfulness

Josef

 

$Path = 'S:\0test' #Root path to look for files

$DestinationPath = "C:\"

#Grab a recursive list of all subfolders = seznam složek a podsložek

$SubFolders = dir $Path -Recurse | Where-Object {$_.PSIsContainer} | ForEach-Object -Process {$_.FullName}

#Iterate through the list of subfolders and grab the first file in each

ForEach ($Folder in $SubFolders)

{

$FullFileName = dir $Folder | Where-Object {!$_.PSIsContainer} | Sort-Object {$_.LastWriteTime} -Descending | Select-Object -First 1

#For every file grab it's location and output the robocopy command ready for use

ForEach ($File in $FullFileName)

{

$FilePath = $File.DirectoryName

$FileName = $File.Name

robocopy $FilePath $DestinationPath $FileName /S /R:6 /W:30 /Z

}

}

Overwrite a variable with a new value

$
0
0

I have this piece of code that sits in a ForEach-Object loop ($Exists is a SamAccountName)

#Gets the User's Manager and gets the Name instead of the DistinguishedName (as it is easier to read), skips if ADUser Manager attribute is empty.

 

$LM=Get-ADUser$Exists-Properties*|Select-Object-ExpandPropertyManager

If ($LM){

$Manager=Get-ADUser$LM|Select-Object-ExpandPropertyName

 

#Confirm Output

write-host"Manager: $Manager"

}

 

The problem is that all the other variables in the loop get overwritten but because the Manager field in AD can be empty $LM doesn’t get overwritten until a new value of $LM is found.  So how do I reset $LM for each loop or force overwriting it. I tried put in $LM=$Null but that didn’t seem to work.

msnpallowdialin to "control access through NPS network policy"

$
0
0

HI , 

 want to change the value to msnpallowdialin "not set" , i know this will results in "control access through NPS network policy"

 

how do i do this using :

 

set-aduser username  -replace @{msnpallowdialin=????}

 

 

replace string in file

$
0
0

Hi, i wrote this lines:

(Get-Content $fullpath) | Foreach-Object {

      $_ -replace 'host=door1', 'HOST = exaprd-scan'`

          -replace 'service_name = prod.xyz.co.il', 'SERVICE_NAME = dwh_prd'`

           } | Set-Content $fullpath

when I run this code I get this result:

HOST = exaprd-scan

SERVICE_NAME = dwh_prd.xyz.co.il

 

I can't understand why it is not replacing the all string "service_name = prod.xyz.co.il" with 

"SERVICE_NAME = dwh_prd", why I still get the suffix "xyz.co.il"?

Thanks

 

Veil-PowerView

$
0
0

I was led to PowerShell in the past few years as it began to rise to prominence in the information security community. As a penetration tester and red teamer for Veris Group’s Adaptive Threat division, my job depends on keeping abreast of current attack tools, tactics, techniques and procedures, and PowerShell is definitely the ‘new hotness’ in infosec.

Read More


PowerShell: Setting the global reading pane view in OWA

$
0
0

Attached is a script that can be used to update the global reading pane view for OWA, and can be run against multiple mailboxes from PowerShell.

Read More

New Script remove members administrator

$
0
0

good afternoon 
Working for a private bank and need to develop a script that do the following. 
I'm starting to develop in Power Shell script. 

I need the script to check my machines in the network through a notepad and list the members of the administrator group and return me what are these groups and after that it lists the members of the administrator group, I want the same script except through a list Notepad members of these groups. 

example: 


server: am4545sr001 
Domain: copr.dominio.com.br 
adm member: domain \ g am4455 dividata 
domain \ g am4455 test 
             domain \ g am4455 administrators 
domain \ adm g am4455 computers 



Since the right to become members of the administrator 

server: am4545sr001 
Domain: copr.dominio.com.br 
adm member: domain \ g am4455 dividata 
domain \ g am4455 test 
            



Aims to assist me? 


sds,

Capture all process output and display it

$
0
0

Hi all

Going round in circles here, help please.

I'm wanting to capture the out put of an exe (so I can email it after) and also display it. Am I missing something obvious?

So here's an example of how far I've got with a good old ping.

$Process = New-Object system.Diagnostics.Process
$Process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo("ping","127.0.0.1")

$Process.StartInfo.RedirectStandardOutput = $true
$Process.StartInfo.RedirectStandardError = $true
$Process.StartInfo.UseShellExecute = $false

$Process.Start() | Out-Null

echo "Live output, missing last out put..."

while (!$Process.HasExited){
   Write-Host $Process.StandardOutput.ReadLine()
}

$stdout = $Process.StandardOutput.ReadToEnd()
$stderr = $Process.StandardError.ReadToEnd()

echo "`nI want to show all out put in variables not just the end...`n"

Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"

This out puts this though. I want it to both out put everything as it goes along and also save everything to the variable to email later:

  • the final out put is not displayed as it goes along (as it HasExited)
  • ReadToEnd is just showing what was missed on point 1
Live output, missing last out put...

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

I want to show all out put in variables not just the end...

stdout:
Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

stderr:

Thank you!

New Scripts list remove members

$
0
0

good afternoon 
Working for a private bank and need to develop a script that do the following. 
I'm starting to develop in Power Shell script. 

I need the script to check my machines in the network through a notepad and list the members of the administrator group and return me what are these groups and after that it lists the members of the administrator group, I want the same script except through a list Notepad members of these groups. 

example: 


server: am4545sr001 
Domain: copr.dominio.com.br 
adm member: domain \ g am4455 dividata 
domain \ g am4455 test 
             domain \ g am4455 administrators 
domain \ adm g am4455 computers 



Since the right to become members of the administrator 

server: am4545sr001 
Domain: copr.dominio.com.br 
adm member: domain \ g am4455 dividata 
domain \ g am4455 test 
            



Aims to assist me? 


sds,

activate windows

$
0
0

Hi gurus

I am looking for the following, as you can see on my first post, I am learning PS.

 how can I get this done, I would like to have PS read a text file with a bunch of computer names and then find out if the machine has been activated or needs to be activated, is it possible to accomplish this using IP address range?

I hope some of you have done this and can share a script/process that I can follow.

 

Thanks a bunch gurus. great day!!!!

windows-powershell-getprocess

Compare a property of one CSV to a different property in another CSV

$
0
0

Hi everyone, I've been trying get my head around this and can't work it out. 

 

I have two CSV files which I would like to compare. The problem is the lines are ordered differently in each in file so I'm not sure how to compare the correct lines. Sometimes certain lines won't exist so I figured reordering the file first may not work. 


For example: 

 

CSV1 (assigned usage)

Name,RAM,CPU,

Geoff.5GB,2,

Bob,2GB,2,

Fred,2GB,2,

Paul,2GB,1,

 

CSV2 (actual usage)

Name,RAM,CPU,

Bob,2GB,2,

Fred,4GB,2,

Geoff,10GB,2,

 

I need to compare these two files and report on who is using more RAM (and Ideally CPU) than they are assigned. In the example above, Geoff is using 10GB of RAM in CSV2 but is only allocated 5GB ins CSV1.

 

I was trying to loop through the first CSV but I'm not sure how to compare to the correct line in CSV2.

 

I have no idea what I'm doing but I started with:

 

$file1 = import-csv "C:\CSV1.csv"

$file2 = import-csv "C:\CSV2.csv"

 

foreach ($line in $file1) { 

if ( ($file2.Name -eq $line.Name) -and ($line.'RAM' -gt $file2.RAM)) { write-host "Good" }

else { write-host "Bad"} 

}

 

Any ideas on how I can achieve this? 


CSV ping formatting.

$
0
0

Ok.. so I am very new to PS. in fact this is my first script so bare with me.

What I am trying to do is run a script that will ping a list of devices if from a csv file, then output the results to another csv file.

My csv is two columns, Ip and description of device.

Ip,Device

192.168.192.168,location

issue is that when I run the job, it runs but adds the two columns together into one column.

 

"Register","Ping Status"
"IpAddress,Register","Failed"
"132.239.75.1,Revelle.Conf.Desk.1","Failed"
"132.239.75.16,Revelle.Conf.Desk.2","Failed"
"132.239.75.18,Revelle.Conf.Desk.3","Failed"
"132.239.75.12,Revelle.Conf.Desk.4","Failed"

If I remove the column "Register" the it runs fine and everything pings but since it is adding the two columns into one, it fails.

#

Get-ContentC:\Users\user\Desktop\ipCSV.csv|ForEach-Object {

if(Test-Connection-ComputerName$_-Quiet-Count 2) {

New-Object-TypeNamePSCustomObject-Property @{

Register=$_

'Ping Status'='Ok'

}

}else {

New-Object-TypeNamePSCustomObject-Property @{

Register=$_

'Ping Status'='Failed'

}

}

}|Export-CsvC:\Users\user\Desktop\POSPingStatus.csv-NoTypeInformation

 

 

 

 

 

who is logged

$
0
0

how do I getout whoiscurrently logged on.I'm interested inthesamaccountname.The variable $computerisalready definedas a computername

Thanks

Marek

Show all printer connections and delete all Xerox

$
0
0

Hello,with thiscodeI getonly displayedthelocalprinter connections.How do I getthenetwork printervisible.I want to deleteallXeroxdrivers sincethey cause Problems

Get-WmiObject win32_printer -ComputerName $Name

Thanks

Marek

powershell inventory script sometimes writes empty csv

$
0
0

ive written a powershell script that runs at pc startup to grab various inventory details from a pc and save it to a scv file on a server.  In testing it works fine but when deployed i keep finding that after a few days he csv file is empty and nothing will add data to it thought the date stamp on the fie updates.  the code is below im reasonably convinced its something in the section that adds altered data back to the file  rather than the sections that create a new file or add a new line if a line for that pc dosent exist as the main place this happens is on a bunch of pcs thats ive tested and all have existing data(have #'d that section out as a test in one location im trying it but awaiting results). 

Im new to powershell having done a bi of vbs scripting in the past but the code looks sensible to me (granted it probably not the best bit of coding ever but i can follow it all easily) i just cant work out why it every few days chucks a wobbler and writes an empty file

# system info ps v1
#locate output file & define default values
$filepath="\\server\share$\outputfile.csv"
$dop="-"
$warantyyears="-"
$warantyend="-"
$location = "-"
$file=""
$csvout=""
$arrayloc=""
$newline=""

#import existing file if it exists

if(test-path -path $filepath)
{
$fileexists="true"
$file = Import-Csv $filepath
}

if(!(test-path -path $filepath))
{
$fileexists="false"
}

# get mac address active cards (tested on multinics)
$mac= Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'ipenabled = "true"' | Select macAddress
if ($mac.count) {$mac3=$mac.macaddress[0] + " : " + $mac.macaddress[1]} else {$mac3=$mac.macaddress}

# get processor and pc name
$procinfo = Get-WmiObject Win32_Processor
$cpuname=$procinfo.Name
$pcname=$procinfo.SystemName

# get memory info/model/make
$pcinfo = Get-WmiObject Win32_ComputerSystem
$maker=$pcinfo.Manufacturer
$model=$pcinfo.Model
$ram=$pcinfo.TotalPhysicalMemory/1024/1024/1024
$ram = "{0:N1}" -f $ram

#get serial no
$serial=Get-WmiObject Win32_BIOS
$serial2=$serial.SerialNumber

#hdd size and free in gb rounded to nearest whole no
$hdddata=Get-WmiObject Win32_LogicalDisk -Filter 'deviceid="c:"'
$freespace=$hdddata.FreeSpace/1024/1024/1024
$freespace = "{0:N0}" -f $freespace
$totalspace=$hdddata.size/1024/1024/1024
$totalspace = "{0:N0}" -f $totalspace

# get windows version
$os=Get-WmiObject Win32_OperatingSystem | select caption
$os2=$os.caption

#date-time
$now= Get-Date
$now2 = $now.date

#create csv data if no existing file
if ($fileexists -eq "false")
{
    #echo "new file created"
    $csvout = New-Object psobject
    $csvout | add-member NoteProperty Macaddress $mac3
    $csvout | add-member NoteProperty PCName $pcname
    $csvout | add-member NoteProperty Manufacturer $Maker
    $csvout | add-member NoteProperty "PC Model" $model
    $csvout | add-member NoteProperty Processor $CPUName
    $csvout | add-member NoteProperty Memory $ram
    $csvout | add-member NoteProperty "HDD Size" $totalspace
    $csvout | add-member NoteProperty "HDD Free" $freespace
    $csvout | add-member NoteProperty "Serial No" $serial2
    $csvout | add-member NoteProperty "Windows Version" $os2
 $csvout | add-member NoteProperty "Date Collected" $now2
    $csvout | add-member NoteProperty "Date purchased" $dop
    $csvout | add-member NoteProperty "Warranty years" $warantyyears
    $csvout | add-member NoteProperty "Warranty Expiration" $warantyend
    $csvout | add-member NoteProperty "Location" $location

    $csvout | export-csv $filepath -notypeinformation #-Append
}

if($fileexists -eq "true")
    {
    $arrayloc=[array]::indexof($file.pcname, $pcname)
    if (!($arrayloc -eq -1))
        {
        #echo "replacing data"
        #$file[$arrayloc] |Format-Table
        $file[$arrayloc].macaddress=$mac3
        $file[$arrayloc].pcname= $pcname
        $file[$arrayloc].Manufacturer=$maker
        $file[$arrayloc]."pc model"=$model
        $file[$arrayloc].processor=$cpuname
        $file[$arrayloc].memory=$ram
        $file[$arrayloc]."hdd size" = $totalspace
        $file[$arrayloc]."hdd free" = $freespace
        $file[$arrayloc]."serial no" = $serial2
        $file[$arrayloc]."Windows Version" = $os2
  $file[$arrayloc]."Date Collected" = $now2
        $file | export-csv $filepath -notypeinformation
        }
    if ($arrayloc -eq -1)
        {
        #echo "adding new line"
        $csvout = New-Object psobject
        $csvout | add-member NoteProperty Macaddress $mac3
        $csvout | add-member NoteProperty PCName $pcname
        $csvout | add-member NoteProperty Manufacturer $Maker
        $csvout | add-member NoteProperty "PC Model" $model
        $csvout | add-member NoteProperty Processor $CPUName
        $csvout | add-member NoteProperty Memory $ram
        $csvout | add-member NoteProperty "HDD Size" $totalspace
        $csvout | add-member NoteProperty "HDD Free" $freespace
        $csvout | add-member NoteProperty "Serial No" $serial2
        $csvout | add-member NoteProperty "Windows Version" $os2
  $csvout | add-member NoteProperty "Date Collected" $now2
        $csvout | add-member NoteProperty "Date purchased" $dop
        $csvout | add-member NoteProperty "Warranty years" $warantyyears
        $csvout | add-member NoteProperty "Warranty Expiration" $warantyend
        $csvout | add-member NoteProperty "Location" $location

        $csvout | export-csv $filepath -notypeinformation -Append   
        }
    }

Remote PowerShell for launch script in Cloud environement

$
0
0

Hello,

I try to understand and describe the way to configure and design a Remote Powershell in order to manage email and mobile services on a Cloud Exchange platforme. The Exchange servers are implemented on a Virtual Machine subnet. How can I configure the remote powershell to access to the availlable server (SPOF issue)

Thank you

Jack

 

Viewing all 6937 articles
Browse latest View live