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

Create hash of rolled-up values

$
0
0

I have coded myself into a corner.  I have a script where I read in a bunch of .csv files into a hash that has a number of invoice lines from different invoices, containing 3 keys: UNIT (the item number), QTY (the number of items purchased) and PRICE (the unit cost of the item).  I need to output a summary of the order, with a record for each unique UNIT and the total of the QTYs, like a pivot table.  My newness to Powershell has me frustrated trying to implement the business logic.  All I need to do is look for the presence of the UNIT and add it if not found, or replace the QTY with the sum of the current and new QTY.

But I can't get it to work.  Can anyone post for example code?

Thanks


tom Repetti


Help parse CSV file using powershell to create Report

$
0
0

I have an excel file that holds some information on several computers.  I was hoping to figure out a way to get some needed information and create some calculations that I've been able to create with the use of this forum.

SERVER_NAMEOSDISK_DRIVE
Server01Microsoft Windows Server 2008 R2 Standard  Service Pack 1C:^116.03 GB Total^45.18 GB Free^S:^20 GB Total^7.53 GB Free
Server02Microsoft Windows Server 2008 R2 Standard  Service Pack 1C:^59.9 GB Total^22.52 GB Free^S:^20 GB Total^7.35 GB Free
Server03Microsoft Windows Server 2008 R2 Standard  Service Pack 1C:^60 GB Total^29.01 GB Free^S:^20 GB Total^3.35 GB Free
Server07Microsoft Windows Server 2008 R2 Standard  Service Pack 1C:^60 GB Total^21.15 GB Free^D:^274 GB Total^31.42 GB Free^S:^20 GB Total^3.38 GB Free
Server08Microsoft Windows Server 2008 R2 Standard  Service Pack 1C:^60 GB Total^14.59 GB Free^D:^50 GB Total^16.7 GB Free^E:^60 GB Total^31.26 GB Free^F:^40 GB Total^21.54 GB Free^S:^25 GB Total^6.74 GB Free

I'm not sure who to get the data so I can work with the Disk_Drive column.  Every time I use:

import-csv c:\computers.csv, I start getting a bunch of errors.  My guess it's due to the "^" but know sure how to parse those out.

Secondly, I need to break out the C/D/E etc drives so I can calculate SizeGB/UsedGB/FreeGB from the Disk_Drive column.

Please let me know if more data is needed.

Thanks


Jr. Admin

Powershell - Export permissions for folder and share?

$
0
0

I need to export all the share and folder level permission on one of my windows 2008 file servers. I have tried the command below and it give me all the folder and file level permissions.

Get-ChildItem "X:\Share" -recurse | Get-Acl | export-csv c:\djk\share_folder_permission.csv

I dont want file level permissions, only share and folder level.  Can you help?

 

 

Wildcard seems to work differently between Windows 2012 R2 and Windows 2008 R2

$
0
0

When I run the PowerShell command 'get-childitem -Path C:\inetpub\logs\LogFiles\u* -recurse' on a Windows 2012 R2 server I get a list of any log files whose names start with the letter u contained in the folder and subfolders of the path above.  The same command in a Windows 2008 R2 server lists nothing unless I remove u* from the path.  Both servers have files with names which start with the letter U in the folder and sub folder in the above mentioned path.  I am confused.  Can anyone explain why this is? Why the command string does not work the same way in both operating systems?  Please accept my gratitude and thanks.

...Jim

Executing a script calling a module from task scheduler not fully working

$
0
0

Hello,

We have a module that checks the datetime of certain backup files to make sure they are written within the past 3 days, then if it finds it, it will execute a lot of SQL stored procs from within Powershell.  This works fine when I manually execute it, but it doesn't execute past the import-module command when I call it from task scheduler.

Task Scheduler action: Start a Program
Program/Script: C:\Windows\system32\WindowsPowerShell\v1.0\Powershell.exe

Arguments: -noexit C:\Scriptsfolder\DBrefresh.ps1 #Leaving noexit for testing. Fails with or without.

When it finishes, I see that it imported the modules but none of the actions are taken.  Here is the script that I'm using to call the module.

param(
$SI = "localhost\QAInstance",
$BUPath = "\\backuppath\BackupsSubFolder\env\blah",
$DBN = ("Database1","Database2")
)

#Import-Module DBRestore -verbose -force
DBRestoreExecutor -BackupPath $BUPath -ServerInstance $SI -DBName $DBN
I have tried it with commenting out import-module and it still has the same effect.


How to Connect to One Server, Extract Data, Connect to Second Server, and Insert that Extracted Data into Table on Second Server

$
0
0
I have the following code that connect to my Central Management Server and loops through each server extracting data and inserting into a table on a different server.  I only want to connect to one server, extract data, connect to a second server, and insert that data into a table on that second server.

I am new to PowerShell and I have been trying to tweek the code below to do this.  However, I have been unsuccessful.  Can anyone help me learn how to do this or point me to a web page demonstrating this?




<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
    Any object can be piped to Out-DataTable
.OUTPUTS
   System.Data.DataTable
.EXAMPLE
$dt = Get-Alias | Out-DataTable
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0   - Chad Miller - Initial Release
v1.1   - Chad Miller - Fixed Issue with Properties
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
    [CmdletBinding()]
    param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)

    Begin
    {
        $dt = new-object Data.datatable  
        $First = $true 
    }
    Process
    {
        foreach ($object in $InputObject)
        {
            $DR = $DT.NewRow()  
            foreach($property in $object.PsObject.get_properties())
            {  
                if ($first)
                {  
                    $Col =  new-object Data.DataColumn  
                    $Col.ColumnName = $property.Name.ToString()  
                    $DT.Columns.Add($Col)
                }  
                if ($property.IsArray)
                { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }  
                else { $DR.Item($property.Name) = $property.value }  
            }  
            $DT.Rows.Add($DR)  
            $First = $false
        }
    } 
     
    End
    {
        Write-Output @(,($dt))
    }

} #Out-DataTable




Import-Module “sqlps” -DisableNameChecking



  

foreach ($RegisteredSQLs in dir -recurse SQLSERVER:\SQLRegistration\'Central Management Server Group'\CentralManagementServerNameHere\ | where {$_.Mode -ne "d"} ) 

  
$dt = Invoke-sqlcmd -ServerInstance "$($RegisteredSQLs.ServerName)" -Database "tempdb" -InputFile "D:\CMS\Scripts\T-SQL\DatabasesNotIncludedInAvailabilityGroup.sql" | out-DataTable
$dt
# Write data table to database using TVP 
$conn = new-Object System.Data.SqlClient.SqlConnection("Server=ServerWhereRepositoryDatabaseIs;DataBase=CMSRepository;Integrated Security=SSPI") 
$conn.Open() | out-null
"Connected"
$cmd = new-Object System.Data.SqlClient.SqlCommand("dbo.usp_InsertDatabasesNotIncludedInAvailabilityGroup", $conn) 
$cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
#SQLParameter 
$spParam = new-Object System.Data.SqlClient.SqlParameter 
$spParam.ParameterName = "@TVP"
$spParam.Value = $dt
$spParam.SqlDbType = "Structured" #SqlDbType.Structured 
$spParam.TypeName = "DatabasesNotIncludedInAvailabilityGroup"
  
$cmd.Parameters.Add($spParam) | out-Null
$cmd.ExecuteNonQuery() | out-Null
$conn.Close() | out-Null


lcerni

How to set OAB generation schedule to "Never" or "Always" in Exchange 2013

$
0
0

Dear all, thanks for viewing this question, any help is appreciate. 

In exchange 2010, I can set OAB generation schedule to "Never" or "Always" with commands like this:

Set-OfflineAddressBook -Identity "\Default Offline Address Book" -Schedule never

Set-OfflineAddressBook -Identity "\Default Offline Address Book" -Schedule always

But in exchange 2013, it seems that these command don't work. And to set the OAB generation schedule, Exchange 2013 use command like this:

Set-MailboxServer -Identity MBXServer01 -OABGeneratorWorkCycle 01.00:00:00 -OABGeneratorWorkCycleCheckpoint 06:00:00

How to set the generation schedule to "Never/Always"?

Restart-VM

$
0
0

From the W2012 Host computer I want to schedule a restart of one of the VM. I have it working via this command however the 'force' syntax is not a graceful restart...

Powershell.exe Restart-VM BNRVM1 -Force

I would rather do a graceful restart and remove the -Force syntax and instead enter a Y when the prompt is trying to confirm that I want to restart.

Can someone please advise on what the syntax is to have a Y entered instead of the -Force


High-Privileged Accounts

$
0
0
Hello,

I would like to know if there is a powershell cmdlet or script that lists all High-Privileged Accounts in an Active Directory domain?

Thank you.

Retrieve User Session count of Web Application

$
0
0

I was wondering if anyone knew how to or if it is even possible to get a web application user session count?

I can get that session count at the Web Site level by doing

Get-Counter "\\$ServerName\web service($website)\current connections"
Since our web site host an n number of web applications, a user connected to the site but using a specific application, so I would like to know what app they are actually using, is this possible?


If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

Don't Retire Technet

Make Powershell Prompt for Input

$
0
0

Hello,

I'm would like to make some scripts for some of the more common task that I do daily and I was wondering if there is a way to make powershell prompt for input when needed. For example:

Get-Mailbox -Identity | Get-MailboxStatistics | Sort TotalItemSize -Descending | FT displayname, totalitemsize, itemcount, database, -AutoSize

In this script I would need to be able to run it for any user in our company. Is there a way for me to be prompted for the 'Identity' in this script?

Additionally, for another script is there a way to have multiple points where I'm prompted for input. Example:

Add-MailboxPermission -Identity -User -AccessRights FullAccess -InheritanceType All

Would I be able to be prompted for both the 'Identity' and the 'User' input?

Thanks in advance

Exchange Web Services & Powershell - Contact Update Issues

$
0
0

Hi All,

I am using EWS with Powershell for the first time, and although my code works, I have run across an issue I am not able to fix. I am trying to fix users' contacts that have been imported incorrectly from another mail system, which is working fine for most entries. However, when an email address field includes a colon (:) when I call the address using the following:

($contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Address)

it does not read the address. I have identified this doesn't appear to be a code issue, as when I replace the address on the same contact with another, still with invalid characters, such as < and spaces, this works fine. I presume this would be a conflict with the EWS syntax and use of : within the syntax itself.

So just to clarify, if my contact has an email address value of "mailto:firstnamelastname@domain.com" it will not be retrieved, but if it is something like "FirstName LastName <firstnamelastname@domain.com>" it will get retrieved.

I have tried finding a way to separate the "EmailAddress1" part so that the colon included within the address field doesn't affect the script but haven't found a successful way of doing this. I hope all the above makes sense. Is there anyone who is able to direct me to a solution so we can call the email addresses that contain the invalid colons? 

Many thanks,

Mike Parker


Mike Parker | MCSE - Messaging | www.cloudbusiness.com




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.

Powershell - Renaming and Moving Files

$
0
0

Hi

I am new to writing Powershell scripts.

I am moving files (.rpt) from one directory to another directory. I need to insert text "_10yr" in the middle of the file name. I also need to check if the directory does not exist create one. I am using a script file. 

The following is the code that I have currently. The other issue I am getting with it is that Powershell closes instantly as soon as I ran the script file. I tried both the AllSigned and RemoteSigned Execution Policy and no matter what Execution policy I set nothing changes.

Thank you

Set-ExecutionPolicy -Scope Process ExecutionPolicy AllSigned -Confirm

Get-Item .\*.rpt | ForEach-Object { Rename-Item $_($_.Name -replace "dr network_", "dr_network_10yr")}

Read-Host -Prompt “Press Enter to exit”


Delete files on remote server

$
0
0

Hi,

Is there any example to delete files which starting with DA*, and file extension are DLL and DLA?

Thanks,


running powershell on remote machine

$
0
0
how do I run a script that is currently on my desktop to multiple remote machines? Does the script needs to be on the remote machine before it can be executed? wsman is already enabled on all remote machines

Can I export all my users' last login time for Office365 exchange mailbox using Powershell

$
0
0
Can I export all my users' last login time for Office365 exchange mailbox using Powershell? I want it to be exported in a CSV file to be a report so that I can read it easily? Can you provide detailed cmdlets? MS?

could use some help on comparing 2 arrays, and mofifying one based on the results of the compare

$
0
0

I have 2 lists of servers, which are arrays, I am comparing using Compare-Object. I am getting good results, I know what is one list but not the other. The problem is, how do I modify the array based on that information? In the code below I implement the following:

if in NEW and NOT in master, ADD to MASTER (implemented successfully in Compare-NewAgainstMaster)
if in MASTER and NOT in new, DROP from master (code is present, but not working in Compare-MasterAgainstNew)

My problem is, in Compare-MasterAgainstNew, I know what servers should be dropped from $arrMaster, it's in $arrDifference. I'm just not sure the best way to do it. I'm not feeling great about this code, so any input and critique is appreciated.

note: I've been using $x as a place to put a break stop

function Get-MasterServers
{
	Param($path)

	#reset new master array
	$script:arrMasterServers = @()

	$sourceMaster = get-content -path $path

	if ($sourceMaster.length -eq $null)
	{
		#file is empty
		Write-Host -ForegroundColor cyan "Master file is blank, will not try to load it"
	}
	else
	{
		$script:countMasterServers = 0

		foreach ($line in $sourceMaster)
		{
			#declare array to hold object temporarily
			$temp = @{}
			$tempLine = $line.Split(",")

			#get and assign values
			$temp.Client = $tempLine[0]
			$temp.Agent = $tempLine[1]
			$temp.Backupset = $tempLine[2]
			$temp.Reason = $tempLine[3]
			$temp.DateAdded = $tempLine[4]
			$temp.DaysOld =  $tempLine[5]

			#write temp object to array
			$script:arrMasterServers += New-Object -TypeName psobject -Property $temp

			#increment counter
			$script:countMasterServers ++
		}
	}
}

function Compare-NewAgainstMaster
{
	#Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
	#Write-Host "Total entries (arrNewServers): $($countNewServers)"

	$customDate = Get-Date -Format yyyyMMdd

	$arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
	if ($arrDifferent -eq $null)
	{
		Add-Content -Path c:\CustomScripts\SLA\sla_new_$($customdate).txt -Value "No new servers to add."
	}
	else
	{
		#determine differences and modify master list
		foreach ($item in $arrDifferent)
		{
			$line = $item.client + ", " + $item.agent + ", " + $item.backupset + ", " + $item.reason + ", " + $item.DateAdded + ", " + $item.DaysOld

			#create file with just new servers to email later
			Add-Content -Path c:\CustomScripts\SLA\sla_new_$($customdate).txt -Value $line

			#add new servers to master
			Add-Content -Path c:\CustomScripts\SLA\sla_master.txt -Value $line

			$script:countDifferenceNewAgainstMaster ++
		}
	}
	$x = "added servers to master"
}

function Compare-MasterAgainstNew
{
	Get-MasterServers -path c:\CustomScripts\SLA\sla_master.txt

	#if in arrDifferent it can be removed from the master list
	$arrDifferent = Compare-Object $script:arrNewServers $script:arrMasterServers -PassThru

	if ($arrDifferent -eq $null)
	{
		Write-Host "No differences found when comparing Master against New, no servers to drop off"
	}
	else
	{
		#create new master list

		#delete old master
		Remove-Item -Path c:\CustomScripts\SLA\sla_master.txt -ErrorAction SilentlyContinue

		foreach ($item in $script:arrMasterServers)
		{
			if ($item.client -eq $script:arrDifferent.client)
			{
				#do not add to new master list
			}
			else
			{
				#add servers to master
				$line = $item.client + ", " + $item.agent + ", " + $item.backupset + ", " + $item.reason + ", " + $item.DateAdded + ", " + $item.DaysOld
				Add-Content -Path c:\CustomScripts\SLA\sla_master.txt -Value $line

				$script:countServersDropOff ++
			}
		}
		$x = "created new master based on arrDifferent"
	}
}

Powershell specifiy a literal "encrypted standard string"?

$
0
0

Hi,

How can I use powershell and manually define a "encrypted standard string" directly without having to read it from a file
then convert it to a secure string.

See my example Method 1 works but I can't get Method 2 to work.

Any suggestions - as I would like to use a secure string in a script without reading it from file or prompting the user.
So just specify the long sequece of characters.

Thanks,

Ward

Here is the error I get:

 ConvertTo-SecureString : Input string was not in a correct format.
At C:\Users\Ward\OneDrive\Documents\test1.ps1:27 char:23
+ $file_data = $data2 | ConvertTo-SecureString
+                       ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertTo-SecureString], FormatException
    + FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

### Code ######

# Method 1 - this works. $pw = ConvertTo-SecureString 'hello' –asplaintext –force $data1 = $pw | ConvertFrom-SecureString $data1 | Out-File -FilePath ".\pw.txt" -Force $file_data = Get-Content ".\pw.txt" | ConvertTo-SecureString $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($file_data) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) "Password: $PlainPassword""" $data1 # Method 2 - use literal text $data2 = @" 01000000d08c9ddf0115d1118c7a00c04fc297eb010000006060907f48c4004f9e68712619c245c6000000000200000000001066000000010000200000006be4552c3584b727a58b044097670bda284c5aac7f 5db1b06d1e3629776a343e000000000e80000000020000200000006b178fa1c6f34251470d87887dd05f16d6d78ccd6be97f758a9fcca28177bf9610000000ca823ec7d654009b5640553b99e614eb40000000 f86406ac343fb8a9f016e516490cc59d441af7bc760ddc19a74779275a8da347909c3df7e3a67304aa50a5a5ae71dc11cfae42ed21a7f50a54b309a2106b0ef0"@ $file_data = $data2 | ConvertTo-SecureString $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($file_data) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) "Password: $PlainPassword"


win32reg_addremoveprograms issue

$
0
0

I currently have SCCM installed and am trying to use WQL queries with SCCM using the win32reg_addremoveprograms class. My issue is, when I test using a powershell query, the 32 and 64 bit queries both return 64 bit applications and no 32 bit applications. Example:

Get-WmiObject -Query "Select * from Win32Reg_AddRemovePrograms64 where DisplayName like '%Java%'" | select DisplayName

Get-WmiObject -Query "Select * from Win32Reg_AddRemovePrograms where DisplayName like '%Java%'" | select DisplayName

Both of these return the same list, and they are all 64-bit applications, and I do have java 32 and 64 bit versions installed.

Viewing all 21975 articles
Browse latest View live


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