the script below outputs my desired info except that the Folder.Parent is the same for all entries instead of the actual entry in the supplied CSV file.
$FolderList = "C:\FolderList1.csv" $FolderSizes = "C:\FolderSizes1.csv" $Folders = Import-csv $FolderList -Delimiter "," $oOUtputItems = @() foreach ($Folder in $Folders.Fullname) { Write-Host "Calculating folder size for: " -NoNewline; Write-host $Folder -ForegroundColor Green $FolderSize = (Get-ChildItem $folder -file -Recurse -ErrorAction SilentlyContinue | Measure-Object -property length -sum -ErrorAction SilentlyContinue) $Parent = (@($Folders.Parent) | Out-String).trim() $oOUtputItems += New-Object -TypeName PSObject -Property ` @{ 'Parent'=($folders.Parent) Folder = $Folder; 'Size in MB' = (("{0:N0}" -f ($FolderSize.sum / 1MB))) } | Select-Object Parent, Folder, 'Size in MB' | Export-csv -NoTypeInformation $FolderSizes -Append } Invoke-Item $FolderSizes
ExportCSV Column Object Not Exporting
VBScript to Change Hostname and join the system to Domain for Windows 10
controlling record devices in Windows
I've played with the command line utility NIRCMD.EXE and found it very effective at manipulating level and mute controls that appear under the "playback devices" tab of the sound window of Windows 7. BUT I need to find a way to manipulate the controls found under the "record devices" tab. Can this be done with Power Shell, or is there some other command line utility that I've overlooked that will give me access to these particular handles? I'm working with a virtual sound card driver that provides four inputs and four outputs for AES67 IP audio. In Windows 7 the driver places the level and mute controls for the four inputs under the "record devices" tab where I am thus far unable to access them via command line. Any suggestions would be appreciated.
Folder/File permissions report
I've been asked by our apps team to export all the file and folder permissions along with the paths to a flat file that they can import it into sql and do reporting on, is there a way to use powershell to grab the permissions that they can use? I've figured out how to do a simple export of the folder/file paths but no with any permissions associated.
Thanks
powershell prompt changes to two greater than signs (>>)
I typed this into a command window:
get-item -literalPath\\IPAddress\folder | get-acl
with valid values inserted for IPAddress and folder.
The system immediately rolls back with a prompt of two greater than signs and nothing else happens.
I typed in a simple dir after a while and hit enter, it returns the two greater than sign prompt again. I have to exit and restart powershell.
Several hours of searching on the web yielded nothing.
What does this prompt mean?
Any help is appreciated.
To export Skype for business online users
Hi,
I need PS command to export Skype for Business online users who is having different SIP and email address.
Thanks in Advance.
Regards,
MS
Is there a way to convert powershell script to VB script ?
Hi All,
I wonder if it's possible to convert the following PS script to a VB script ?
(get-childitem -path env:computername).Name +":" + (get-childitem -path env:computername).Value| out-file "c:\tpm\$env:COMPUTERNAME.csv"
Thank you.
Get-ChildItem
I am trying to list out all child folders from a CSV list of server shares. The output will be read by another script to get the child folder sizes however, the output file is also populated with the server share root folder. How do I prevent the root share from being added to the output file? Script:
$InputFile = "C:\Temp\Intput.csv" $OutputFile = "C:\Temp\Output.csv" Import-Csv $InputFile | ForEach-Object{ Write-Host "Listing child folders from: " -NoNewline; Write-host $($_.FullName) (Get-ChildItem $_.FullName | Where-Object { ($_.PSIsContainer) } | Select-Object -Property Parent, Fullname) [PSCustomObject]@{ Parent = $_.Parent; 'FullName' = $_.FullName; } }| Select-Object Parent, 'FullName' | Sort-Object Parent, 'FullName' | Export-csv -NoTypeInformation $OutputFile # The input file format is: # # "Parent","FullName" # "Share1$","\\Server\Share1$"
# "Share2$","\\Server\Share2$"# The output file shows as follows # "Parent","FullName" # "Share1$","\\Server\Share1$" # "Share1$","\\Server\Share1$\Backups" # "Share1$","\\Server\Share1$\Restricted" # "Share2$","\\Server\Share2$" # "Share2$","\\Server\Share2$\Data"
# "Share2$","\\Server\Share2$\Test"
Script to download email attachment
I have a Powershell script that runs nightly to download a report that is emailed to the mailbox. The report is attached to the email and comes in two formats. XML and CSV. I am trying to add another parameter to the script to only look for the CSV attachment. Would anyone have insight on how to add this additional parameter? The script is attached.
Current Script proccess
1. Logs into a mailbox
2. Searches for an email that is a. unread, b. contains a subject of "Report:" and c. has an attachment
3. It downloads the attachments to a file share
4. Moves the email from the Inbox to the Deleted Items
Script Code
$MailboxName = "mailbox@domain.com" $Subject = "Report" $downloadDirectory = "\\server\fileshare" Function FindTargetFolder($FolderPath){ $tfTargetidRoot = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName) $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot) $pfArray = $FolderPath.Split("/") for ($lint = 1; $lint -lt $pfArray.Length; $lint++) { $pfArray[$lint] $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint]) $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) if ($findFolderResults.TotalCount -gt 0){ foreach($folder in $findFolderResults.Folders){ $tfTargetFolder = $folder } } else{"Error Folder Not Found" $tfTargetFolder = $null break } } $Global:findFolder = $tfTargetFolder } $dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll" [void][Reflection.Assembly]::LoadFile($dllpath) $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1) $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">" $aceuser = [ADSI]$sidbind $service.AutodiscoverUrl($aceuser.mail.ToString()) $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName) $InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid) $Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead, $false) $Sfsub = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject, $Subject) $Sfha = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::HasAttachments, $true) $sfCollection = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And); $sfCollection.add($Sfir) $sfCollection.add($Sfsub) $sfCollection.add($Sfha) $view = new-object Microsoft.Exchange.WebServices.Data.ItemView(2000) $frFolderResult = $InboxFolder.FindItems($sfCollection,$view) foreach ($miMailItems in $frFolderResult.Items){ $miMailItems.Subject $miMailItems.Load() foreach($attach in $miMailItems.Attachments){ $attach.Load() $fiFile = new-object System.IO.FileStream(($downloadDirectory + “\” + "Report.csv"), [System.IO.FileMode]::Create) $fiFile.Write($attach.Content, 0, $attach.Content.Length) $fiFile.Close() write-host "Downloaded Attachment : " + (($downloadDirectory + “\” + "Report.csv")) } $miMailItems.isread = $true $miMailItems.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite) $miMailItems.delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::MoveToDeletedItems) }
Powershell crash with Set-Acl and XAML form
I made a graphical interface with XAML and PowerShell to set some ACL and everytime I run the command Set-Acl it crashes.My XAML have a few textbox and the one I'm using here is serviceTB (it's the department for which I wan to create a root folder) and folderTB being the folder name. The function getGPath is a custom function to retrieve the UNC path of the department.Here is the function I am calling with the last line causing the issue (PowerShell does not respond and crash ISE+console), do you have an idea why?
New-ADGroup -name "CONTOSO\$($WPFserviceTB.Text)ACL$($WPFfolderTB.Text)R" -path $ouData -GroupScope Global -ErrorAction Stop
$description = "L:\$($WPFfolderTB.Text) W access"
Set-ADGroup -identity "CONTOSO\$($WPFserviceTB.Text)ACL$($WPFfolderTB.Text)R" -Description $description
sleep(10)
$path = getGPath $WPFserviceTB.Text
$Acl = Get-ACL -Path $path
$ADObject = New-Object System.Security.Principal.NTAccount("CONTOSO\$($WPFserviceTB.Text)ACL$($WPFfolderTB.Text)R")
$permissions = 'ReadAndExecute, Synchronize'
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($ADObject, $permissions, $InheritanceDefaultFlag, $PropagationFlag, $objType)
$Acl.AddAccessRule($objACE)
Set-Acl -path $path -AclObject $Acl
Global variables:
$InheritanceDefaultFlag = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
Change default formatting of output from PowerShell script
I have a PowerShell script intended for testing a web application. It outputs various types of objects that contain data parsed from HTTP responses. I want the script to display this data by default, so that I can see what it is doing, and I also want to be able to capture the output to a variable so that I can examine the properties of the objects in more detail.
When I am not capturing the output of the script to a variable or piping it to a cmdlet, PowerShell 5.1 appears to format the output as if I had piped it to Format-Table, which chooses the columns of the table based on the properties of the first object. My problem is that the other objects have entirely different properties and Format-Table generally does not display them at all.
I can simulate the behavior by using this command:
@( [System.Tuple]::Create(10); [System.Collections.Generic.KeyValuePair[[Int],[Int]]]::new(20, 21); ) | Format-Table
The output is:
Item1 Length ----- ------ 10 1
That is, the Key and Value properties of the KeyValuePair object do not appear at all. The same happens if I omit the Format-Table invocation. In contrast, if I pipe the objects to Format-List, then the output is more useful:
Item1 : 10 Length : 1 Key : 20 Value : 21
How does PowerShell decide to use Format-Table to format the output?
Can I put something in the script to make PowerShell default to Format-List instead, while retaining the ability to pipe the original objects to other cmdlets?
Getting / Separating Group Owners
Hi there, after many hours of scouring here and elsewhere on the Interwebs, I'm very stuck and wouldn't be posting if I could find a way on my own. Here's the issue:
1. Find all groups where a specific user is an owner (done)
2. From those groups, list only owners who are not admin (admin accounts are in the format of "username_a" and my team's admin accounts are 'owners' of all DG's and SG's
3. After extracting only the end users who are owners, re-apply the 'managedby' permissions with those end users from step 2, and a new security group.
For step one, I'm using:
Get-DistributionGroup * | Where-Object {$_.managedby -like "*lemmen*"} | select name,managedby -first 10
A) This successfully gives me a list of the DL name, and the complete list of 'managedby', as intended.
B) The user 'lemmen' was one of our admins, but no longer, hence wanting to identify groups where that name is still attached as an owner.
My question is: How do i do steps 2 and 3 above? I need to extract the end user owners' Usernames (samaccountname), so getting just their usernames is the first challenge, and then how do I take THOSE results and re-apply them to the original list of groups from step 1?
I've even tried exporting the list of group names from #1 to a .csv, then reading from that and running this:
% {Get-DistributionGroup $_.name | select name,managedby}
OR
% {Get-DistributionGroup $_.name | select name -expandproperty managedby}
but all that does is give me a list of the owners in formats I don't want
PS: I'm not interested in the Get-ADGroup and the single ManagedBy field results, thanks
Any help would be very much appreciated, thank you!
Parse through a directory and identify and copy.move files to an archive folder
I have a dilemma and dont really have a clue how to solve this.
I have been given the task to remove a list of files
They are in a one parent directory C:\data1\data2
however the files are individually located in numerous nested directories
C:\data1\data2\folder1\folder2\xxx.exe
C:\data1\data2\folder1\folder2\folder3\file.zip
C:\C:\data1\data2\folder1\folder2\folder3\xxx.txt
I receive the files names in a spreadsheet and copy the path to a holding file named removal.txt
I tired using the following script to identify the files and populate them (this way i can produce to data owner for verification)
Get-childItem -Path C:\data1\data2\* -Recurse -include(Get-Content "C:\data1\data2\removal.txt") -verbose |Out-File -filepath "C:\data1\data2\\utput.txt"
when i run this query i dont get any output
however if i only insert the file names in the removal.txt i.e.
xxx.exe
file.zip
xxx.txt
i get the output with the data required
what do i need in order for this to work?
Priyantha Perera
Monitor Antivirus Software With Powershell.
Hello Everyone,
I'm new to this community and working on powershell script.
I am planning to create powershell script for windows server which will monitor antivirus software installed on the server,
can any one suggest the checks I have to perform to conclude that antivirus software is installed and working properly.
Script will be specific for Windows Servers from Windows server 2008 to Windows Server 2016.
Regards,
Nirav Sachora
ADSI WinNT get User properties
I want to read Network Access Permission property value of local user account (Local Users and Groups ► Properties ► Dial-in tab) at WS2012r2 in workgroup environment.
I run this vbscript:
OnErrorResumeNextSet usr = GetObject("WinNT://<Workgroup_name>/<computer_name>/<user_name>,user")
WScript.Echo "Parameters "& usr.Parameters
WScript.Echo "RasPermissions "& usr.RasPermissions
WScript.Echo "DialinPrivilege "& usr.DialinPrivilege
WScript.Echo "msNPAllowDialin "& usr.msNPAllowDialin
WScript.Echo "MaxDisconnectionTime "& usr.MaxDisconnectionTime
and get only:
Parameters m d P♣▲∟☺msNPAllowDi
alin?????????????☺CtxCfgPresent????☺CtxCfgFlags1????☺CtxShadow????*☻☺CtxMinEncry
ptionLevel?
MaxDisconnectionTime 60
— just msNPAllowDialin mentioned in Parameters string value, but in unreadable form.
How can I accomplish this?
How to open and close IE using PowerShell?
Does anyone have any suggestions?
Thanks in advance for any suggestions
Thanks in advance for any suggestions
I need to know if and where a certain user account was being used to run a service, a scheduled task or an application pool
Need to know if and where a certain user account was being used to run a service, a scheduled task or an application pool from a list of computernames in a csv.
Please help just looking for an easy script to use.
Storing the variable values from Foreach loop in single variable
I have a situation where i wanted to take users attribute and store the values in Single variable so that i can pipe it out for other function. But i couldn't do that. Help please.
Here is my code:
$LicenseUsers = Get-MSOLuser | where {$_.Islicensed -eq "True"}$Users = ($licenseusers).Userprincipalname
foreach ($User in $users)
{
$usagelocation = Get-msoluser -userprincipalname $user | Select Usagelocation
}
I want $usagelocation to have values like below instead of showing only the last one value.
Usagelocation1
Usagelocation2
Usagelocation3
I have tried using $usagelocation+= Which adds all the value in single row instead of multiple values.
Register for Caps Lock indicator light
Where is the value of state of capslock stored? More specifically the capslock indicator light. If I wanted to programmatically have the light turn on and off where should I look for that value?
Thanks,
Zach
Searching IIS Logs For Outlook Anywhere Connections
Hi everyone,
We have enabled advanced IIS logging on our Exchange 2016 servers and I've been tasked with preparing a report from those logs showing users that connect from external IPs using Outlook Anywhere. Ideally we want the report to show usernames for the last 30 days. Since we enabled advanced logging in IIS our log files have massively grown in average size (some at 4GB) and that makes searching through the logs much harder. We have 11 Exchange servers and searching across all of them for the last 30 days is extremely slow. I wrote a PowerShell script to do this and in an attempt to make the output file smaller I am excluding internal and private IP addresses. Here is the script:
$Servers = Get-ExchangeServer | Select Name | Sort Name ForEach ($Server in $Servers) { $logs = $ServerName = $Server | %{$_ -replace '@{Name=', ''} | %{$_ -replace '}', ''} $log_path = "\\" + $ServerName + "\d$\inetpub\logs\LogFiles\W3SVC1" $logs = Get-ChildItem $log_path -Recurse -Include *.log | ? { $_.LastWriteTime -gt (Get-Date).AddDays(-30) } | Select Name ForEach ($log in $logs) { $logname = $log | %{$_ -replace '@{Name=', ''} | %{$_ -replace '}', ''} $filename = $log_path + "\" + $logname Get-Content $filename | %{$_ -replace '#Fields: ', ''} | ?{$_ -notmatch '^#'} | %{$_ -replace 'Source-IP', 'SourceIP'} | ConvertFrom-Csv -Delimiter ' ' | Select date,time,s-ip,cs-method,cs-uri-stem,cs-uri-query,s-port,cs-username,c-ip,'cs(User-Agent)','cs(Referer)',sc-status,sc-substatus,sc-win32-status,time-taken,SourceIP | Where-Object{$_.SourceIP -notmatch "^10.|^192.168.|^172.|^-"} | Export-CSV \\FileServer\ExchangeLogs\HugeCombinedIISLog.csv -NoTypeInformation -Append } }
The output file is still huge, well over 100GB, and I don't have anything that can open a file that size. I thought about further restricting the search to {$_.cs-uri-stem -eq '/rpc/rpcproxy.dll'} but I'm not entirely sure how to do that. How do I include search criteria with the Where-Object statement above while also excluding IP addresses?
Can anybody please offer any assistance here?
Thanks