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

Powershell Patching Information: Problems using Export-CSV / looping

$
0
0

I've made a simple script that obtains patching information from a series of servers.

The csv file I use to reference my servers is called patchlevels.csv and just contains some basic information.

ServerName,OS,ServicePack,Patches,,,,,,,
SERVER1,Server 2003 R2 Enterprise,SP2,,,,,,,,
SERVER2,Server 2003 R2 Enterprise X64 Edition,SP2,,,,,,,,

Yup, that's exactly as its formatted ^

The problem I am having is updating the Patches column with a link to the server-specific htm file (I figure I can always save as xlsx within Excel to get clickable hyperlinks). I have failed multiple times over the last few hours using export-csv to try and update the Patches cell(s).

Here is my script minus any failed export-csv references for clarity's sake:

$currentPath = "$pwd\"
$HostFileName = "patchlevels.csv"
$CSVLoc = $currentPath + $HostFileName

    Import-Csv "$CSVLoc" | ForEach-Object {

    Write-Host "Processing..."
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    $ServerName=$_.ServerName
    $ServerFile = "$ServerName.htm"
    $OS=$_.OS
    $ServicePack=$_.ServicePack
    $_.Patches = $_.Patches.replace("[","$ServerFile")

    Write-Host "Server Name: $ServerName"
    Write-Host "Operating System: $OS"
    Write-Host "Service Pack: $ServicePack"
    Write-Host "Processing Patch List"
    wmic /node:$ServerName /output:$ServerName.htm qfe list

    Write-Host "Patch List generated for $ServerName"
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    }

    Write-Host "END PROCESSING"

I can see two things that may be wrong:

1) Formatting of my CSV file (,,,,,,)

2) I am not sure about the formatting of $_.Patches = $_.Patches.replace("[","$ServerFile")

And obviously, I'm missing the export-csv commands to update the patchlevels.csv file with the htm file location (which is what this entire post is about).

Where would I put export-csv in this code to update my original csv as the script runs?

Thanks in advance for any help with this.

Kind Regards,

Stephen


Access to the path '\\server1\c$\file1.csv' is denied.

$
0
0

Hi everybody,

I'm trying to figure out what could cause the issue in Title. Still without progress.

From Server1 I'm executing this code in powershell ISE:

Invoke-Command -ComputerName Server2.domain.com -scriptblock { Get-Process  | Export-Csv \\Server1.domain.com\c$\File1.csv }

Then I will get the: "Access to the path '\\Server1\c$\File1.csv' is denied." error message.

Server1 = Windows 2008 R2

Server2 = Windows 2012 Std.

It's very strange, because if I use as Server2 the Windows 2008 machine, it works smoothly. But if I use another machine that run under Windows 2012 then it fails with above error.

I have read many related topics but without any relevant answer.

No, it can't be the double hop issue as I run the script from server1 against server2, but file I'm trying to save back to server1, not to other server(server3).

Is something different on Windows 2012 that needs to be set or configure to avoid of this issue ?

Enable-PSRemoting -Force - done

Executionpolicy set to unrestricted

Both servers uses TrustedHost = * in WinRM config

WinRM quickconfig - done on both servers.

Adding a file to each users Home Drive

$
0
0

Afternoon

I have a directory with over 200 users listed within (it is their homes drive)

i wish to place a file i have in each users home drive using powershell

however i have the path \\locationtohomedrivearea\users.name

Basically what i want to happen is to copy a file from a central location to each individual users drive above but i appear to have issues with powershell creating a full path for each individual user

My syntax i am using is as follows

$root = "locationtousershomedrivearea"
$user = GCI $root
foreach($user in $users){
$fullpath = "$root" + "\" + "$user" }

Write-Host $fullpath

I could then use the full path to move a file to for each user and in future re use this to rename files within the users home drive etc

if you could point me in the right direction that would be great

Barrie

Local Security Policy List

$
0
0

Hi,

For the last couple of days I was looking for a powershell script to list secpol.msc -> Local Policy -> User Rights Assignments or Account Policy for a list of given server(2008)/workstations(Win7). This turned out to be tougher than expected, hence this post. I have come across

Get-WMIObjectRSOP_UserPrivilegeRight

But this only displays the enabled settings not all of them. I also checked the secedit but this does not work for remote computers.

What I really like is the list of policy and its Security Settings values, e.g.

Policy Name                               Security Settings

Log on as a batch job                 Administrator, Backup...

logon as a service                      everyone

Maximum password age             30 days

etc

...

If you can direct me to the cmdlets that allow to retrieve the above info then that will be great, I already scripted to loop through a computerName list but just need to gather the security policy for each computer

 Many Thanks in advance

 

Cant save excel file

$
0
0

$importcsv = Join-Path "$PSScriptRoot" "data.tsv"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.OpenText($importcsv)

$wb.SaveAs("data.xlsx")

Im getting the error 

You cannot call a method on a null-valued expression.

Excel is opened as it should, it just will not save it.

Add-ADGroupMember : A referral was returned from the server???

$
0
0

I'm sure I'm missing something here...

All I want to do is add a user from a child domain to a universal distribution group in a parent domain.  Sounds simple enough right?  WRONG!

Here is the example that the help gives:

-------------------------- EXAMPLE 4 --------------------------

    C:\PS>$user = Get-ADUser "CN=Glen John,OU=UserAccounts,DC=NORTHAMERICA,DC=FABRIKAM,DC=COM" -Server "northamerica.fabrikam.com";
    $group = Get-ADGroup "CN=AccountLeads,OU=UserAccounts,DC=EUROPE,DC=FABRIKAM,DC=COM -Server "europe.fabrikam.com";
    Add-ADGroupMember $group -Member $user -Server "europe.fabrikam.com"


    Description

    -----------

    Adds the user "CN=Glen John,OU=UserAccounts" from the North America domain to the group "CN=AccountLeads,OU=UserAccounts" in the Europe domain.



What I can gather from this is that what I am trying to accomplish SHOULD be possible however I'm missing something critical.  Here is the command I'm trying to run:

Add-ADGroupMember -Identity "CN=Test-Group,OU=Area 51,DC=rootdomain,DC=int" -Members "CN=Homer Simpson,OU=TEST,DC=childdomain,DC=rootdomain,DC=int"

And here is the Error that I'm getting:

Add-ADGroupMember : A referral was returned from the server
At line:1 char:1+ Add-ADGroupMember -Identity "CN=Test-Group,OU=Area 51,DC=rootdomain,DC=int ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ResourceUnavailable: (CN=Test-Grou...DC=rootdomain,DC=int:ADGroup) [Add-ADGroupMember], ADReferralException+ FullyQualifiedErrorId : ActiveDirectoryServer:8235,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

I've tried adding the:

  • -Server "dc01.rootdomain.int:3268"
  • -Server "rootdomain.int:3268"
  • -Server "rootdomain.int"
  • -Server "dc01.childdomain.rootdomain.int:3268"
  • -Server "childdomain.rootdomain.int:3268"
  • -Server "childdomain.rootdomain.int"

I am logged in as an Enterprise administrator however one of the next things I'm going to try is to pass my credentials to the command.  Any thoughts as to what might be going on?

Powershell Script to check the status of Autheticated Internet site

$
0
0

Powershell Script to check the status of Autheticated Internet site, (Which needs credentials) 

Script has to check, Site is working or not.



Exclude list of users from get-aduser cmdlet

$
0
0

Hello,

I need to put some exclusion for my input data

Lets say, I don't want to list "test01, test02, test03" users.

I can write it like

get-aduser -filter * |?{$_.name -ne "test01" -and $_.name -ne "test02" ..}

Im sure there is more candy-like way to accomplish this.

Something like
$exclude = @('test01','test02')
get-aduser -filter * |?{$_.name -notmach $exclude}

Propably I find the answer myself soon,  but im in hurry and need it to resolve that fast.. 


Need to extract all users from an AD group and then pass off their UserPrincipalName to another cmdlet

$
0
0

Say I have an AD group called "group1" and I'd like to get all members and then pass off their UserPrincipalName (samaccountname + domain name) to another cmdlet, what would be the best method for that? I'm working with a cmdlet that will accept a single UserPrincipalName or an array, so right now I have this:

$group4 = Get-ADGroupMember SAMPLE-GROUP
    foreach ($user in $group4){
    $getuser = get-aduser $User
    $user = $getuser.userprincipalname
    add-tpuser $group4 -Verbose
    }

There's got to be an easier way, though.

Thanks.


zarberg@gmail.com

Get-ChildItem directory only (not full path) on error output

$
0
0

Hello,

I currently use the snippet below to check for folder permissions, it outputs a CSV file which details Category, Reason and TargetName. When I open my error.csv file I see the 3 columns being populated, but how can I get a 4th column with the directory name as well? TargetName outputs the complete path to the folder, I want to also include the directory name in the CSV.

$Path = "C:\test"

$errors=@()
get-childitem -recurse $Path -ea silentlycontinue -ErrorVariable +errors | Out-Null
$errors | select -expand categoryinfo | select category,reason,targetname | export-csv -NoTypeInformation -Delimiter “,” .\error.csv

Any help would be appreciated. At this point I dont think getting the directory name only is feasible with my method. I've tried many exampled but cant seem to get it. As easy as it may sound.

Thank you.


get-eventlog

$
0
0

I'm trying to read the last 7 days of relevant Security log entries on one of my DCs and I'm getting the following error. Is there a way to accommodate all the data that's being returned? I don't explicitly declare $eventlog as a particular variable type.

Clear-Variable -name eventlog
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (eventlog:String) [Clear-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.ClearVariableCommand
 
Get-EventLog : Log "Security" could not be read to completion due to the following error. This may have occurred because the log was cleared while still being read. Index 81445 is out of
bounds.
At D:\tsg\Documentation\Powershell Repository\adaudit.ps1:163 char:13
+ $eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -In ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ReadError: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : LogReadError,Microsoft.PowerShell.Commands.GetEventLogCommand
Get-EventLog : No matches found
At D:\tsg\Documentation\Powershell Repository\adaudit.ps1:163 char:13
+ $eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -In ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand

...and here's a snippet of the relevant code:

foreach ($domaincontroller in $domaincontrollers){

Clear-Variable -name eventlog

#517,624,626,630,632,633,634,636,637,642,644,660,661,671
$eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -InstanceId 1102,4720,4722,4726,4728,4729,4730,4732,4733,4738,4740,4756,4757,4767 -After ((Get-Date).AddDays(-7)) | select TimeGenerated,InstanceID,Message

# ---- Members added to Domain Local Groups ----
                $MyReport += Get-CustomHeader "1" "Members added to Domain Local Groups on domain controller $domaincontroller"
                        $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.InstanceID -eq "4732"} | select TimeGenerated,Message  )
                $MyReport += Get-CustomHeaderClose

$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose

Thanks in advance,

Greg

$ADSI.comitchanges() - A constraint violation occurred

$
0
0

Hi,

I'm trying to manage OU permission using powershell, I have $ace object created using following command:

$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($OUAdminsSID,"CreateChild,DeleteChild","Allow",,"All")

The result seems correct:

ActiveDirectoryRights: CreateChild, DeleteChild
InheritanceType: All
ObjectType: 00000000-0000-0000-0000-000000000000
InheritedObjectType: 00000000-0000-0000-0000-000000000000
ObjectFlags: None
AccessControlType: Allow
IdentityReference: S-1-5-21-XXXXXXXXX-XXXXXXXXXX-725345543-533952
IsInherited: False
InheritanceFlags: ContainerInherit
PropagationFlags: None

however following command result in error:

$ADSI.psbase.ObjectSecurity.AddAccessRule($ACE)
$ADSI.psbase.commitchanges()

Exception calling "CommitChanges" with "0" argument(s): "A constraint violation occurred.
"
At line:1 char:1
+ $ADSI.psbase.commitchanges()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Now the funny part: this problem occurs only in of our AD domains, it works fine in two others. And also this commands works just fine:

dsacls "OU=Country,OU=Countries,DC=Domain,Dc=COM" /G domain\superuser:CCDC /I:T


How can find internet explorer version

$
0
0

Hi Team,

I am looking script which can find internet explorer version . I need to run this script among 1000 servers.

can anyone help me on this .....?


Regards, Triyambak

list members and properties from multiple AD groups

$
0
0

Hi - I need to create a csv that lists the members from multiple AD groups and for each member shows their displayname, username, distinquished name etc

So far I've got a script that lists members for each group:

$Groups = Get-ADGroup -Properties * -Filter * -SearchBase <path to OU>
Foreach($G In $Groups)
{
    Write-Host $G.Name
    Write-Host "-------------"
    $G.Members
}

But how do I modify this to display the properties for each user and also output to a csv?

Any help much appreciated

J

 

Users and their AD groups listed

$
0
0

I'm new to PowerShell. I need to have an AD power shell script that can generate a .csv output with users and their AD groups.

Any assistance will be greatly  appreciated.

Thanks.

Write-Output:  Person, Name, ManagerName, ManagerEmail, $group


Uninstall a sofware with registry uninstall string from Control Panel

$
0
0

Hi,

I created that registry key (export from registry to reg file):

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\!Vcredist2005_Frv1]
"DisplayName"="!Vcredist2005_Frv1""DisplayVersion"="2005""InstallDate"="2015-02-05""Language"="Fr""Publisher"="""UninstallString"="powershell -executionPolicy bypass -noexit -file \"C:\\Program Files\\xxx\\yyyyyyyyyyyyy\\zzzzzzzz\\Vcredist2005_Frv1\\Vcredist2005_Frv1_DesInstMan.ps1\"""NoModify"=dword:00000001"NoRepair"=dword:00000000"NoRemove"=dword:00000000

Everytime, I am trying to uninstall the software, I get an error saying the software seems to not being intall. At command prompt the command line is not working. I would like being able uninstalling software from control panel.

Any idea of what I am missing?

Thanks,

François




File copy from multiple server to a common repository share

$
0
0

Hi ,

    I am looking for a power shell script that will copy content from multiple server and paste to a common share in a remote server .

Requirements :

  • Script should read from a file that contains server names
  • Create a directory (SERVER NAME ), if one does not exist in the same target below
  • Move all the folders/files to the target
  • Report any errors (files that could not be moved due to permission or “in use”) .

Thanks

Bibin

Simply get computer name with serial number

$
0
0

Hi All,

I use the script below to get serial number, but I have no idea how to get the computer name in the meantime.

Pls point me.

$File = [System.IO.File]::OpenText("d:\111.txt")
 while($Machine = $GuyFile.ReadLine())
{Get-WmiObject -computername $Machine win32_SystemEnclosure }
$GuyFile.Close()

Trying to create a script for a Backup - no success

$
0
0

Hello Community,

This is my first entry here and I hope I´m doing it correct.

My intention is to create a script which copies files from folder A to folder B automatic. every night. It should just copy the changed files, for example Word documents which were edited. Unchainged files should not be touched.

IF there is a changed file, it should copy it, but not overwrite it on the folder B, it should create a file with a date/time extension in the filename.

This is to save older versions of files for the case of mistakes while editing and back up short after. I hope I described it understandable.

Maybe anybody can help me with this, because I have just basic knowledge on Powershell.

Please excuse some grammar mistakes, I´m from germany and not a native english speaking person.

Best Regards,

Tobi

Using Windows Search Index to search for PST files

$
0
0

Hi All,

I have the following script that searches for PST files across all connected drives and lists them in a datagridview

function Get-PSTInfo {
$statusbar.text = "Searching "
$array = New-Object System.Collections.ArrayList
$Script:pstinfo = Get-PSDrive -PSProvider "filesystem"|%{get-childitem $_.root -include *.pst -r}|select name, fullname, @{name="Size (GB)";expression ={"{0:N2}" -f ($_.length/1GB)}} 
$array.AddRange($pstinfo)
$dataGrid1.DataSource = $array
$dataGrid1.autosize = $false
$form1.refresh()
$statusbar.text = "Finished Searching"
$array|Export-Csv c:\temp\pstfound.csv -notypeinformation
}

This takes about 45 minutes to run when tested and I wanted to know if it is possible to use the search index to speed this up as that brings up the same results in about 30 seconds.

I have had a look around and the examples I can see don't seem to work for me

Can anyone help?

TIA

Andy

Viewing all 21975 articles
Browse latest View live


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