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

Parsing Get-WinEvent "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"

$
0
0

i'm trying to get the logon,logoff,connect, disconnect info from the above log.  Here is what i have so far:

 Get-WinEvent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | where {($_.Id -eq "21" -OR $_.Id -eq "24" -OR $_.Id -eq "25"  -OR $_.Id -eq "23")} | Export-Csv C:\RDS.csv


Then I just wanted these columns and i put them in a diff csv:

Import-Csv C:\RDS.csv | select Message,TimeCreated | Export-Csv -Path c:\FixedRDS.csv –NoTypeInformation

Now i have two columns:

MessageTimeCreated

Message consists of multi-line, and Timcreated is just a single.

There's probably a better way that two diff .csv files to get to this point, but i'm just starting out here.  The objective is to parse out the Message line into muliple columns: I'd like the first column to be Message and the value in the above example to be "Sesseion has been disconnected" I suppose that could just say "disconnected", but eitherway that value.  The next column would be "User", then I don't need the "Session ID" or "Source Network Address" (though this doesn't eve show up on each record). The last column would be "TimeCreated" like this:

The end result of this is to insert into a SQL server table. Maybe there is even a better way of doing all of that in one shot. 

Thanks


How to get an ACE entry into Spreadsheet using get-ace

$
0
0

Hi folks. I'm working on a script to pull a server inventory including shares, share permissions, and other entries.

I'm able to retrieve the share and ace entries, but when I try to write them to an excel sheet, they aren't coming over with a readable value.  I can output the info to the screen.  I've tried to use a Switch command like this but it doesn't work -

 
#       Switch($UniqueShare.AccessRights)
#                {
# 1179817 {$Sheet1.Cells.Item($intRowShare, 7) = "ReadAndExecute"}
#   }

Below is a code snip showing what I'm doing.  Any help would be appreciated.

$strComputer = read-host "Enter computer name "
$strComputerDelim = "\\" + $strComputer
$sharelist = get-wmiobject win32_share -ComputerName  $strComputer

foreach ($share in $sharelist)
 {
$ShareAceName = $strComputerDelim + "\" + $share.Name
$ShareAceDetails = get-ace -path $ShareAceName

    foreach ($ShareAce in $ShareAceDetails)
        {
        foreach ($UniqueShare in $ShareAce)
            {
#Populate Shares Sheet (This is only a code snippet)
        write-host $UniqueShare.AccessRights
        $Sheet1.Cells.Item($intRowShare, 7) = $UniqueShare.AccessRights
 $Sheet1.Cells.Item($intRowShare, 8) = $ShareAceDetails.AccessControlType


        $intRowShare = $intRowShare + 1
            }
       }

$intRowShare = $intRowShare + 1

}

Results on screen are like this for the Permissions:
ReadAndExecute, Synchronize
FullControl
ReadAndExecute, Synchronize
ReadAndExecute, Synchronize
GenericExecute, GenericRead
ReadAndExecute, Synchronize

Results in the sheet are like this:
Permission
1179817

Thanks,

Don K


Don K

Use a specfic string that is one of many strings output from a command as variable

$
0
0

Hi, Sorry about a bad title. Didnt know how to title this question.

The case is that I want to run this command in a script for users in different domains: Test-CsAddressBookWebQuery -TargetFqdn $TargetFqdn -UserSipAddress User1$SipDomain -TargetSipAddress User2$SipDomain.

My problem is retrieving the $SipDomain from another command correctly.

I am using the 

Get-CsSipDomain which gives out put like this:

Identity                   Name                                       IsDefault
--------                   ----                                       ---------
somestring   somestring2                  True
somestring3            somestring4                        False

"somestring" is the string I need to get into $SipDomain variable.

I have tried to do 

$SipDomain = Get-CsSipDomain | Where-Object {$_.Isdefault -eq $true} | Select-Object Identity

which gives me output

Identity
--------
somestring

But this does not work in the first command as $SipDomain as I only need the string "somestring" in the variable.

Any tips to how I can achieve my goal?

Would be much apreciated! :)

Copy-item including folder structure and not overwrite

$
0
0

Hi,

I have a script that does a GCI on 4 folders, it then filters out specific file that do not need copying, it then creates the top level folder in the destination folder then copies the file and the -container folder.

The problem I am having is that for each folder in the source if there is folder withing with files or folders in it doesn't get copied.  I've tried -recurse and also -contains for copy-item.

Any ideas?

#root of archive
$root = 'f:\Archive'
#Root plus time stamp folder
$archive = "f:\Archive\Archive_$(Get-Date -f dd_MM_yyyy)"
#Make Destination Datestamp Folder
New-Item -Path $archive -ItemType Directory
#find latest folder
$todayFold = (Get-ChildItem -Path $root | Where-Object {$_.PSIsContainer} | Sort-Object LastWriteTime -Descending | Select-Object -First 1)
$todayFold = $todayFold.fullname
#arrays for path and exclude
$filepath = $Desktop, $MyDocs, $Downloads, $MyRecordings

#copy logic

Foreach ($folder in $filepath){
$folderEnd = split-path $folder -leaf
$fullfinalpath = join-path $todayFold -childpath $folderEnd
CD $folder
New-Item -ItemType directory -Path $fullfinalpath
$Files = GCI -path $folder -recurse | Where-object {$_.name -ne 'cleanup' -and $_.name -ne 'TurningPoint 5' -and $_.extension -ne '.ps1' -and $_.name -ne 'CountDownTimer' -and $_.name -ne 'Templates' -and $_.name -ne 'Cyberlink' -and $_.name -ne 'My Recordings' -and $_.name -ne 'TurningPoint' -and $_.extension -ne '.Lnk'}

#I think this might be the cause

foreach ($file in $files){copy-item -path $file.fullname -destination $fullfinalpath -container} #; remove-item -recurse $file.fullname }

}

#set location for zip (by CD)
set-location $root
#Pass todays archive folder to zip function
create-7zip $todayfold $securepassword
#remove the folder after zipping
#remove-item -recurse $todayfold -ErrorAction SilentlyContinue -Confirm:$false
invoke-item $root


Alter De Ruine


Sort by folder size

$
0
0

Hello every one! I have this script:

$log = ".\logfile.log" 
$startFolder = "C:\VMs"
$colItems = Get-ChildItem $startFolder  | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($i in $colItems){
   $itemSum = Get-ChildItem ("$startFolder\" + $i.Name) -recurse | Measure-Object -property length -sum"$startFolder\$i -- " + "{0:N2}" -f ($itemSum.sum / 1KB) + " KB" >> $log
   } 
import-csv $log -delimiter "`t" | export-csv .\TEST.csv
$body = Get-Content  $log | Sort |  Out-String
Send-MailMessage -From test@test.local -To test1@test.local -Subject "Test Theme" -attachment .\TEST.csv -Encoding ([System.Text.Encoding]::UTF8) -Body $body  -SmtpServer test123.test.local
Remove-Item $log
Remove-Item .\TEST.csv

When this script done I receive something like this in email message:

C:\VMs\Backup -- 0,00 KB

C:\VMs\Vbox -- 82 874 750,42 KB

C:\VMs\VMWARE_BACKUP -- 182 818,77 KB

How I can change this script to sort by folder size? Notalphabetically.

Thanks in advance!


What is the "file signature" of a 16-bit executable ?

$
0
0

What is the "file signature" of a 16-bit executable ?

In other words, what do I need to know about the internals of a 16-bit executable (either a 16 bit xxx.exe or xxx.com file) to write a Powershell function that can tell me if the file is compatible with the 64-bit version of Windows 7 ?

Using get -childitem to scan different drives but append one text file.

$
0
0

Folks,

I need some help, I wrote the below to scan for certain files types on client machines but I cant get the script to scan anything other than the C$. Apologies I am kind of new to scripting and PS. The script is kicked off using a batch file that makes the CR directory on the clients. I think the problem stems from the $disk variable or the way I have used foreach or the loop - any help would be appreciated

Set-Location c:\
$s = new-object -comObject SAPI.SPVoice
$s.speak("Scan in progress")
write-host "Scanning for files"
$Extension = @("*.zip","*.rar","*.ppt","*.pdf")
$Path = "$env:userprofile\Desktop"
$disks = "c$","D$"
foreach ($disks in $disks)
{get-childitem -force -include $Extension -recurs -EA SilentlyContinue >$path\files.txt}
$s.speak("Scan completed")
Write-Host "Scan complete, files.txt created on your desktop - press any key to exit..."
$x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
Remove-Item c:\cr -recurse -EA SilentlyContinue
exit

PowerShell to add a Certificate to "Trusted Root Certification Authorities"

$
0
0

Hi,

I am trying to add a Certificate to the "Trusted Root Certification Authorities" using PowerShell, but haven't been able to accomplish it. I am using the following PowerShell snippet

$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 
$certPath = read-host "Certificate Path"
$pfxPass = read-host "Password" -assecurestring
$pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet") 
$store = new-object System.Security.Cryptography.X509Certificates.X509Store("Trusted Root Certification Authorities","localmachine")
$store.open("MaxAllowed") 
$store.add($pfx) 
$store.close()

I provide the "Certificate Path" as C:\MyCerts\mywildcardcert.pfx" and the "Password" as the private key used when creating the certificate. But after I run this snippet, it gives no errors but doesn't add the Certificate as well.

Strangely it creates another folder called "Trusted Root Certification Authority" and add the Certificate to that. This folder is different from the existing one. Why does it create on with the same name instead of adding it in the existing folder? I am puzzled. Also is there a way to remove that folder? (Screenshot below)


Admin QuikView Solution for CRM 2013




Running PowerShell versions 4 & 3 side by side (sxs)??

$
0
0

Hi,

I have noticed that PS version 4 seems to "replace" version 3. I.e. there is no way to access 3 once 4 is installed.  This differs to how version 2 & 3 operated, which allowed side by side execution.

E.g:

- If you have PS 4 installed, open up a PowerShell console and run "$PSVersionTable". It will list "4.0".

- If you have PS 3 installed, open up a PowerShell console and run "$PSVersionTable". It will list "3.0".

Now, to access PS 2 from either 4 or 3, type "powershell -version 2". Once the nested shell is accessed, again run "$PSVersionTable", it will list "2.0".

However, if you have 4 installed and run "powershell -version 3", $PSVersionTable will continue to return "4.0".

Is this by design? Is there a way of loading PS 3 even if PS 4 is available? I have large scripts which have compatibility issues/behaviour differences with 4 and would like to avoid running on 4 until they have been well tested.

Thanks,

Bardo

Unable to enable HTTPS binding for Website using Powershell

$
0
0

Hi,

I have been trying to enable HTTPS for a website in IIS, but I keep getting the following error:

New-Item : Failed to create SSL binding. Error code 1312.
At line:1 char:85
+ Get-Item cert:\LocalMachine\Root\0D53C58BBC8EEECDAB54D9ACEDF07EE7777F9B26 | New-Item <<<<  0.0.0.0!443
    + CategoryInfo          : InvalidData: (:) [New-Item], ProviderException
    + FullyQualifiedErrorId : Failed to create SSL binding. Error code 1312.,Microsoft.PowerShell.Commands.NewItemComm
   and

I am using the following set of PowerShell commands to enable HTTPS:

Import-Module WebAdministration
New-WebBinding -Name "WebSiteName" -IP "*" -Port 443 -Protocol https

And once HTTPS is enabled, I am using the following PowerShell to wire up the Certificate using its thumbprint:

Get-Item cert:\LocalMachine\Root\0D53C58BBC8EEECDAB54D9ACEDF07EE7777F9B26 | New-Item 0.0.0.0.!443

When doing via UI, it works fine. But using PowerShell gives the above mentioned error. Any idea why this is happening and how to solve this?


Admin QuikView Solution for CRM 2013

How to obtain verbose and debug log from powershell, without modifying code

$
0
0

Hello, 

I have the following issue: In a Xenapp citrix environment, i have published some applications that run a powershell scipt from the server. This powershell script run an executable. Normally, uses connect and can start the program but sometimes it fails but nothing is written to the Event log and no information is logged. I would to have a extensive debug log of what happens when the user run this command, having a debug log (verbose) of the powershell scripts that run on the server. Is there any that can be added to the powershell command line  (that runs from Citrix command line console) to get the extensive debug log without altering the powershell code??

The command is:

powershell.exe -file C:\GTS\appname\foldernam\myscript.ps1   ANY PARAMETER?

Please help

Thanks in advance

Convert to HTML - Help with formatting

$
0
0

Hello, I have a txt file which list Windows services, and when opened in notepad, word etc all the columns line up correctly.  I would like to add this txt file to an HTML report.  I'm aware ConvertTo-Html is not appropriate function for this, but anyway I did try :

$textfile = "C:\services.txt"
$htm = "c:\services.htm"
$import = import-csv  $textfile -delimiter "`t"
$import |  ConvertTo-Html | Out-File $htm,

I've also tried adding <br> tags at the end of each line and whilst the data is readable it's not alligned (same as the convertto-html).  Can anyone assist with any Powershell methods for retaining some basic table formating when moving data from a txt file to html?  The input data has to be the txt file.  Hoping I do not need to specify each table row, table data references on each element and that someone has a trick!

Script to show access to all shared folders on a server

$
0
0

I was asked by management the other day to come up with a list of what departmental shares our Helpdesk has access to (not sure why, was just asked to come up with the list). This can be either via direct ACL entries or via group membership. Luckily I was only asked to get the top (departmental) level, I.E. all our departmental shares are in one location, and I only need to show the first level down.

Since I'm posting here, obviously (or maybe not) I've decided to do this in PowerShell.

I'm thinking what I need to do is get a list of each member of the Helpdesk AD group and for each one do the following:

  1. Show any access that they have directly
  2. List the groups they are members of
  3. Show any access those groups have

Maybe I'm focusing too much on the 10' view when I need to be looking at the 30,000' foot view, but I can't wrap my brain around how to do this.

Any suggestions? I have a couple of code snippets to get ACLs and get groups for a given user, I guess I need to just nest a bunch of "foreach" statements and then figure out a way to format the whole pile for presentation?


zarberg@gmail.com

How to handle error from unsupported WMI query?

$
0
0
    $deviceid = (gwmi win32_logicaldisk -filter "Name='$drvltr'").`
        GetRelated('Win32_DiskPartition').GetRelated('Win32_DiskDrive') | 
        foreach { $_.PNPDeviceID }
    $predict = gwmi -Namespace root\wmi -class MSStorageDriver_FailurePredictStatus | 
        Where-Object { $_.InstanceName -like "$deviceid*" } | foreach { $_.PredictFailure }

I use the above code to get PredictFailure status for each volume as part of an inventory script.  The problem is not all drives support SMART.  What is the best way to test/handle this to avoid throwing an error?

The error I get is this:

gwmi : Not supported... $Predict = gwmi -Namespace root\wmi -class MSStorageDriver_FailurePredictStatus... +CategoryInfo : Invalid Operation [Get-WmiObject], ManagementException..

Importing multiple users for linked exchange accounts

$
0
0

This is for Exchange 2013 SP1 FYI

Ok, I am lost on this script...

I am trying to do a linked mailbox from a different forest using a CSV file. I can re-export the CSV if I need to gather other information.

Can I set all the attributes when I create the mailbox or do I need to have a separate line or script to set the attributes?

I know my import-csv is messed up but I am not sure how to fix it.

Script:

Import-Csv .\file.csv |foreach {

New-Mailbox -Database "uh-xchdb1" -Name "$_.DisplayName" -DisplayName “$_.DisplayName” -FirstName “$_.GivenName” -Initials “$_.Initials” -LastName “$_.Surname” -ExternalEmailAddress $_.EmailAddress -Title “$_.Title” -Department “$_.Department” -OfficePhone “$_.OfficePhone” -Fax “$_.Fax” -MobilePhone “$_.MobilePhone” -Alias "$_.SamAccountName" -LinkedDomainController "dc1.domain1.com" -LinkedMasterAccount health\$_.SamAccountName -OrganizationalUnit Users -UserPrincipalName $_.UserPrincipalName -LinkedCredential:(Get-Credential domain1\john)

}

csv file:

UserPrincipalName,SamAccountName,DisplayName,GivenName,OtherName,Initials,Surname,EmailAddress,Title,Department,OfficePhone,Fax,MobilePhone

testaddev2@domain1.com,testaddev2,Test I. Addev2,Test,,I,addev2,testaddev2@emailaddress.com,Sr VP,MIS,505-111-111,505-222-222,505-333-3333



DSC Package resource handling EXE (not MSI)

$
0
0

I am working through using the built-in Package resource provider for Desired State Configuration and I am having issues with using .EXE files with it (not MSI).

I see no failures in Trace-xDscOperation and I also don't see any attempt at processing the package, nor any errors with the attempt.

.EXE don't have 'ProductId' as a property (not the GUID that an MSI has) so I am a little confused as to how to set this up properly.

All of the documented examples are with MSI packages, not EXE.


Brian Ehlert
http://ITProctology.blogspot.com
Learn. Apply. Repeat.
Disclaimer: Attempting change is of your own free will.

AD objects have $ symbols as leading character

$
0
0

Hi,

I hope this is the correct place to ask this question

I am fairly new to PowerShell and am trying to perform a Get-ADComputer lookup on a specific OU in my domain, however the OU's are named $Servers for example.

So when I run...
Get-ADComputer -LDAPFilter "(name=*)" -SearchBase "CN=$Servers,DC=contoso,DC=com"

I receive the following error
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADComputer], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

I have tried some other ways of presenting the value such as `$Servers to no avail.

Can anyone advise how to do this.

Many thanks.

Offce 365: Assigning calendar permissions via security groups/bulk calendar sharing

$
0
0

I originally posted this in the 365 forums but was informed to post it here instead...

I'm looking for a way to do bulk calendar sharing of individual calendars (not Public Folders) in Exchange Online.

I have a client looking to share every employee's calendar with every single employee in their organization.

They have 16 employees so if I did the usual PowerShell command below I'd have to enter it some 250+ times.

Add-MailboxFolderPermission –Identity user1@domain.com:\Calendar -AccessRight Editor -User user2@domain.com

I created a security group and added all of the employees to it.  Now if I can run a PowerShell command to assign calendar permissions to that security group and I can drastically cut down my admin work.  In theory I can run the PowerShell command one time for each staff member (so 16 times) and have all of the necessary permissions assigned.

If that method isn't possible then what's the best practice for getting this done?

Copy new and updated files

$
0
0

how can I do in powershell the following

I had

 SourceFoler  = d:\temp\SourceFolder

TargetFoler = d:\temp\TargetFolder

OtherFolder = d:\DiffernceFolder

I want to copy new and updated files from source folder to target folder

AND

Capture ONLY these updated and new files and copy them to "Other folder"

How I can do that ?

Thanks in advance

multiple AD domain recursing search from datatable

$
0
0

Hi all,

Can someone help about this problem :

I have a datatable in a datagridview, I want to search the username from the mail address.

I'm able to find what I need if my datatable have only users in a single domain but if I have 2 mail addresses with 2 different domains I have only records from the last line.

I do not know how to recurse the search for each line and pass the searchroot property according to the value of User_LDAP_Mail column

I hope I'm clear...

here is my function :

Function LDAPSearchUserNameViaMailAddress
{

$DataGrid.Name = $MyInvocation.MyCommand
AddRemoveColumns -TableType $DataGrid.Name

# Build LDAP Query with the mail address #

[String]$ldapQuery = "(&(objectCategory=user)(|"

$data = $global:dt.Rows | Where {(($_.User_LDAP_Mail -ne "") -and ($_.User_LDAP_Mail -ne $null) -and ($_.User_LDAP_Mail -ne [System.DBNull]::Value))}
$data | % {
		$ldapQuery = $ldapQuery + "(mail=" + $_.User_LDAP_Mail + ")"
		if ($_.User_LDAP_Mail -match "@domain1.com") {$SearchRoot = "LDAP://dc=domain1,dc=forest,dc=com"}
		else { $SearchRoot = "LDAP://dc=domain2,dc=forest,dc=com"}
}
$ldapQuery = $ldapQuery + "))"
if ($data -ne $null)
{
	$data.item |Get-Member -Verbose |Out-GridView -Title "data"
	$de = new-object system.directoryservices.directoryentry($SearchRoot)
	$ads = new-object system.directoryservices.directorysearcher -argumentlist $de,$ldapQuery
	$ads.PageSize=1000
	$complist = $ads.findall()
	$complist | % {
		#$_.properties.name; $_.Path 
		$adsresult = $_
		$global:dt.Rows | Where {$_.User_LDAP_Mail -eq $adsresult.properties.mail} | % {
			$dtrow = $_
			$dtrow.UserName = $adsresult.properties.samaccountname[0]
			$dtrow.User_LDAP_Name = $adsresult.properties.name[0]
			$dtrow.User_LDAP_Mail = $adsresult.properties.mail[0]
			#$dtrow.User_LDAP_DN = $adsresult.Path 
			[String]$str_LDAP_DN = $adsresult.Path
			$dtrow.User_OU = $str_LDAP_DN.Substring($str_LDAP_DN.IndexOf("OU="))
		}
	}
}
}


Thanks


Viewing all 21975 articles
Browse latest View live


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