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

Backup before overwriting

$
0
0

Hi!

I'm trying to create a script that copies files to a file system, but before overwriting any file, it first should save it in a backup folder. I started trying with "Compare-Object", but found problems when trying to choose only the files i want to copy. Is there a way to do this with Copy-Item? Or I should keep on fighting to do a list of the different files with compare objects, and then backing up and copying each file one by one?

Thanks


find Joe's 2004 2005 2006 2007 income tax file

$
0
0
find Joe's 2004 2005 2006 2007 income tax file

Dynamically populate powershell switch statement

$
0
0

Hi,

I need help dynamically creating switch statement selections.

I can do this OK.

$ar = "RED","GREEN"

$ANS = (Read-Host "Choose from these $ar")
Choose from options RED GREEN: RED
$ANS
RED
switch ($ANS){

GREEN {write-host "GREEN"}
RED {write-host "RED"}
default {write-host "NO GOOD"}
}

RED

But What if I want to dynamically populate the choices of Red and Green from the $ar array? It does not work. For example if I replace this..

"GREEN {write-host "GREEN"}
RED {write-host "RED"}"

with this..

"foreach($y in $ar){
$y
{write-host "$y"}
}"

Purpose to dynamically create the menu contents based on the array and provide actions based on those. My contents are never static.

I assume I can dynamically populate these somehow but I get an error..

Missing statement block in switch statement clause.

Any ideas?


How to compare int32 values (ranges) for overlaps

$
0
0
Wonder it someone could answer this for me. How I can compare all results in ConvertTo-DecimalIP (note there will be 000's to see if any of the int32 values would be in each of the ranges. Note each split is start/end of one single range, I'm looking for overlaps. Yes this is an SCCM thing, but figured the question was more for the powersehll forum. Thank you in advance.
function get_data
{

    $wmi = gwmi -Namespace "root\sms\site_XXX" -Class sms_boundary -Filter "boundarytype='3'" | Select-Object -ExpandProperty value #3 = IP Address Range
           $Target= @()
    foreach($i in $wmi)
    {
        $target += $i    
    }
    foreach($first in $Target)
    {
    $result = $first.split('-')
        foreach($res in $result)
        {
            #Write-Host $res
            ConvertTo-DecimalIP $res
        }
    }

}




Function ConvertTo-DecimalIP {
     
  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress
  )

  Process {
    $i = 3; $DecimalIP = 0;
    $IPAddress.GetAddressBytes() | ForEach-Object { $DecimalIP += $_ * [Math]::Pow(256, $i); $i-- }

   return [UInt32]$DecimalIP
  }
}

get_data


set two variables from single prompt

$
0
0

I am trying to write a script which will provide a single prompt and as a result provide multiple variables. For example I would like to prompt the user to enter their email address and from that input I would like to get the following three variables.

1. $v1 = the full email address

2. $V2 = the part of the address before @

3. $v3 =the domain.

Any suggestions?

Help with string functions

$
0
0

I'm trying to figure out how to change how the table insert works.  Right now, it's just populating 2 columns.  I would like to break up the first column into several columns using substring or something like take the next 3 characters after the"(".  Any help would be appreciated.

#$destserver = "SESQLDEV01"
#$destDB = "Monitor"
param ($destserver, $destDB)
$destserver = "BEAST"
$destDB = "SSIMS_Prod"
###########################################################################################
function Get-SqlData 
{
    param([string]$serverName=$(throw 'serverName is required.'), 
          [string]$databaseName=$(throw 'databaseName is required.'),
          [string]$query=$(throw 'query is required.'))
    Write-Verbose "Get-SqlData serverName:$serverName databaseName:$databaseName query:$query"
    $connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
    $da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
    $dt = New-Object "System.Data.DataTable"
    [void]$da.fill($dt)
    $dt
}
###########################################################################################
function out-DataTable
{
  $dt = new-object Data.datatable  
  $First = $true  

  foreach ($item in $input){  
    $DR = $DT.NewRow()  
    $Item.PsObject.get_properties() | foreach {  
      if ($first) {  
        $Col =  new-object Data.DataColumn  
        $Col.ColumnName = $_.Name.ToString()  
        $DT.Columns.Add($Col)       }  
      if ($_.value -eq $null) {  
        $DR.Item($_.Name) = "[empty]"  
      }  
      elseif ($_.IsArray) {  
        $DR.Item($_.Name) =[string]::Join($_.value ,";")  
      }  
      else {  
        $DR.Item($_.Name) = $_.value  
      }  
    }  
    $DT.Rows.Add($DR)  
    $First = $false  
  } 

  return @(,($dt))

}
###########################################################################################
function Get-WMIInfo 
{ 
param($serverName)
@("\\$serverName\PhysicalDisk(*)\Avg. Disk Read Queue Length", "\\$serverName\PhysicalDisk(*)\Avg. Disk Write Queue Length", "\\$serverName\PhysicalDisk(*)\Avg. Disk sec/Read", "\\$serverName\PhysicalDisk(*)\Avg. Disk sec/Write","\\$serverName\PhysicalDisk(*)\Disk Read Bytes/sec","\\$serverName\PhysicalDisk(*)\Disk Reads/sec","\\$serverName\PhysicalDisk(*)\Disk Write Bytes/sec","\\$serverName\PhysicalDisk(*)\Disk Writes/sec") |% { 
    (Get-Counter $_.replace("*","1 c:")).CounterSamples } | 
    Select-Object Path, CookedValue | `
    add-Member -memberType noteProperty -name Server -value $servername -passThru

} 
###########################################################################################
function Write-DataTableToDatabase 
{ 
    param ($dataTable,$destTbl) 
    $connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;" 
    $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString 
    $bulkCopy.DestinationTableName = "$destTbl" 
    $bulkCopy.WriteToServer($dataTable) 
} 
###########################################################################################
Get-SqlData $destserver $destDb "Select ServerName From ServerNames" |
foreach {
    $dataTable = Get-WMIInfo $_.servername | out-datatable 
    if ($dataTable) 
    { Write-DataTableToDatabase $dataTable 'PhysicalDisk' } 
}

Desired State Configuration Custom Resources

$
0
0

After reading this article http://blogs.msdn.com/b/powershell/archive/2014/01/03/10469575.aspx I downloaded the attachment and created my first custom resource.

https://github.com/jeffpatton1971/Desired-State-Configuration/tree/master/resources/DSCResources/FileIO_Copy 

The MOF file is generated and the code in the .psm1 appears to work properly. The issue i have is I think my test-targeresource cmdlet isn't working properly. I'm assuming that the params are passed into the code by the DSC process itself, but based on what I've written i don't know if that's a valid assumption.

The code originally just tested for the existing of files in the destination path that matched the filter. In my example we'll talk about *.txt files. This test returned true if any *.txt file existed, so i attempted to adjust the code so that the test was aware of the .txt files in the source and see if they were there in the destination. 

When i manually execute the code it just works the way you would think it does. But when it is run as part of the DSC process it always returns true if any .txt file exists in the destination.

So can someone either shed light on what i may have done wrong inside the code, or she some light on how things are passed around as part of the DSC process. 

Thanks,


Jeffrey S. Patton Jeffrey S. Patton Systems Specialist, Enterprise Systems University of Kansas 1001 Sunnyside Ave. Lawrence, KS. 66045 (785) 864-0242 | http://patton-tech.com

need to export OD and its Sub-OU info in excel format

$
0
0

Hi,

I m using win2008R2 in my organization,we have multipli OU's in AD and inside that OU we have multiple sub-OU's, i want to export all the information of those OU's (for eg:- how many users and computers are there in each OU and sub-OU.)

is there any script or command that i can use to export the OU data in proper.XLS format .?

Regards,

Prashant



Getting detailed user account status in Active Directory

$
0
0

Hi,

I have a script which I use to get the status of an account in Active Directory. This value is collected as follows:

$status = Get-ADUser -Filter 'samaccountname -like $username'    

$obj|Add-Member-MemberType NoteProperty-Name UserStatus-Value$status.Enabled

Now, this only returns a Boolean value, i.e. whether the account in enabled (True) or disabled (False). I'd like to know if it is possible to get a more detailed status for disabled accounts, i.e. "Password Expired", "Locked" or "Disabled".

Is there any way to get these values rather than just true or false?

Thanks!


Powershell Overview

$
0
0

Hi all,

Iam new to windows powershell.I need to learn basic commands using powershell.Please suggest some important urls.

Regards,

Praveen

PowerShell Studio

$
0
0

Is there any other product like Powershell studio in the market?

Please suggest


Abraham ----------------------------- Knowledge is Power


PsSession and empty pipe element

$
0
0

I am wondering if this is by design or not.

Writing a script to format disks remotely by using a PsSession.  Of course, I first try the script locally without a PsSession:

    Get-Disk | 
    Where PartitionStyle -eq 'RAW' |
    Initialize-Disk -PartitionStyle GPT -PassThru |
    New-Partition -UseMaximumSize |
    Format-Volume -FileSystem NTFS -Confirm:$false

Works fine.

After it completes, I run Clear-Disk to start all over.  I go to another machine (same OS level), open a PsSession, and start typing in the commands.  I enter the first two lines as one - Get-Disk | Where PartitionStyle -eq 'RAW' |

But when I enter a carriage return after the pipe symbol, I get this error message:

An empty pipe element is not allowed.

I thought the idea of a PsSession was to create an evironment to execute commands in the same manner as if I were executing them from on that other machine.  Is there a difference in the design model?

Yes, I understand I could put the entire piped command on a single line, but I like to try to make things a little easier to read without scrolling back and forth all the time.  So this is not a critical error.  I'm just curious.

Thanks for the insights.


.:|:.:|:. tim

30 day inactive AD user account & computer report using Powershell

$
0
0

Hello all,

I am a newbie to Powershell and would greatly appreciate it if someone can tell me how to run a report listing all user accounts & computers that's been inactive for the last 30 days.

Search through group members one at a time?

$
0
0

I currently have a script that searches through group memberships using "get-adgroupmember" to see if a group contains a user object, and if so, the script performs an action. However, "get-adgroupmember" has to resolve the entire group membership before my script can search through the members to see if any of the members are user objects. What I would like is to be able to search the members one at a time, instead of having to resolve the entire membership before searching through it. That way, as soon as my script encountered a user object as a member, it could perform its action immediately.

Is there a way to search group members one at a time, instead of having to resolve the entire group membership before searching through them?

For example, the following script would take forever on a large domain:

$member = get-adgroup -filter 'name -eq "Domain Users"'| get-adgroupmember | %{$_.objectclass}
If($member = "user"){"User present"}
I would like to have it where as soon as the above script detected a user object, it could take an action and quit, instead of having to resolve every object inside "Domain Users" first.

Invoking Powershell modules on remote clients via package/command line

$
0
0

Hello Everyone -

I have two modules(functions) that i've written and tested successfully locally in my environment that give me Uninstall and Repair functionality on whatever the string contains. Both .psm1's are delivered via a SCCM pkg that lands both into folders in the Modules directory. My issue is I can't seem to invoke this in a deployment scenario...as i'd like to deliver the "Invoke-command" using SCCM's command line to simply say...

Invoke-Command -scriptblock { Do-This "<string>" }

The above command works fine locally when...(exePol is set to Bypass).
1.)Modules have respective folders living in WindowsPowershell\Modules directory named xxxx.psm1
2.)Import-Module -name <path\name of module>
3.)Verify Modules are loaded(moduleType is script)

But when fabricating the folders\files above with SCCM, and running the Invoke-Command(in many different ways remotely), i recieve the cmdlet, program doesn't exist and has no idea what i'm talking about. Folders\Files for .psm1's are present and do show when running Get-Module -Listavailable locally on targeted clients.

Maybe this is related to the Import-Module command and the context i'm trying to delivery it in?
I've tried multiple scenario's of...

A.) Psexec that launches powershell, followed by the Import-Module -name <path\name of module>
B.) .Bat file that launches powershell with the same Import-Module syntax
C.) PS1 that includes the same Import-Module line.
D.) Just straight from the command line of the Pkg/Program.

Has anyone tried this? Is there a better method when trying to deliver invoke-command on a module/function to a client via SCCM? 

TIA 


Powershell to keep track of process

$
0
0

Hi All,

How can we use pwoershell to track of process for example(explorer.exe)

if process(explorer.exe) is not present it should wait till the process appears and then sleeps for a minute and then exits once the process has started.

Your help is much appreceited


Umeed4u

Fastest way to search through root domain for user objects present in groups?

$
0
0

Hello all. New to PowerShell here, and wanting to be sure my script below is optimized as far as efficiency and speed. I've been searching around the Internet to teach myself various PS components, and have compiled the following script (~80 lines or so). The purpose of this script is to search through the entire domain and find all AD Domain Local Security groups, and then search through these groups to see if any of them have User objects, Owners, or Approvers present in them:

cls
#CREATING RESULTS FILE FOR END RESULTS
$resultsfile = "C:\Results.txt"
Clear-Content $resultsfile

#CREATING THE SEARCH FOR DOMAIN LOCAL SECURITY GROUPS. OBJECT CATEGORY IS
#KEPT IN THE FILTER AS IT HELPS THE SEARCH RUN FASTER.
$strFilter = "(&(objectcategory=group)(grouptype=-2147483644))"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://dc=acme,dc=net")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

#LISTING PROPERTIES I WANT TO RETURN
$PropertyList = "name"
foreach ($i in $PropertyList){$objSearcher.PropertiesToLoad.Add($i)}

$SearchResults = $objSearcher.FindAll()
"Getting search results... Please wait..."

#MAKING COUNTERS THAT ARE ONLY USED FOR SCREEN OUTPUT DURING LOOP
$total = $SearchResults.count
$i=1

#CREATING 3 ARRAYS TO STORE 3 CATEGORIES OF RESULTS
$LocalsWithOwners = @()
$LocalsWithApprovers = @()
$LocalsWithUsers = @()

#LOOPING THROUGH THE INITIAL SEARCH RESULTS TO NARROW DOWN TO JUST GROUP NAMES. HERE IS WHERE I
#FEAR I AM LOSING SPEED AND EFFICIENCY.
foreach ($objResult in $SearchResults)
{    
    $objItem = $objResult.Properties
    $objItemName = $objItem.name

    #TAKING THE GROUP NAMES FROM ABOVE TO SEARCH THROUGH 
    foreach($name in $objItemName)
    {
        "($i of $total) Querying $name..."

        #GETTING 3 CATEGORIES OF VARIABLES
        $member = get-adgroup -filter 'Name -eq $name' | get-adgroupmember | %{$_.objectclass}
        $owner = get-adgroup -filter 'Name -eq $name' -Properties * | %{$_.managedby}
        $approver = get-adgroup -filter 'Name -eq $name' -Properties * | %{$_.ldgMoreGroupManagers}

        #CHECKING VARIABLES AND ADDING TO APPROPRIATE ARRAYS
        If(($member -eq "user") -and ($owner -eq $null)){$LocalsWithUsers += $name} 
        If($owner -ne $null){$LocalsWithOwners += $name}
        If(($Approver -ne $null) -and ($owner -eq $null)){$LocalsWithApprovers += $name}

        #INCREMENTING COUNTER (USED IN SCREEN OUTPUT ONLY)
        $i = ++$i
    }
}

#ADDING ARRAYS TO TEXT FILE WITH HEADERS
Write-output "------------------------------------------------------------------" | out-file $resultsfile -Append
Write-output "The following Local groups have no owner but contain User Objects: " | out-file $resultsfile -Append
Write-output "------------------------------------------------------------------" | out-file $resultsfile -Append
Write-Output $LocalsWithUSers | out-file $resultsfile -Append
Write-output "" | out-file $resultsfile -Append

Write-output "-----------------------------------------" | out-file $resultsfile -Append
Write-output "The following Local groups have an owner: " | out-file $resultsfile -Append
Write-output "-----------------------------------------" | out-file $resultsfile -Append
Write-Output $LocalsWithOwners | out-file $resultsfile -Append
Write-output "" | out-file $resultsfile -Append

Write-output "---------------------------------------------------------------" | out-file $resultsfile -Append
Write-output "The following Local groups have no owner but contain Approvers: " | out-file $resultsfile -Append
Write-output "---------------------------------------------------------------" | out-file $resultsfile -Append
Write-Output $LocalsWithApprovers | out-file $resultsfile -Append
Write-output "" | out-file $resultsfile -Append

notepad $resultsfile

The best way I can figure to output the results is to load 3 arrays with the 3 categories of results, and then output these results to a text file. Can anyone see any ways to optimize this script to make it faster or more efficient? I'm sure there are a TON as I am a PS n00b. Also, if you would, please explain why you made a certain change, as the learning part is the most important part to me. Thanks!





Issues with Powershell WMI - CIM_DataFile

$
0
0

When running VBscript and accessing the AccessMask propert I get a value of 2032127 consistently.  When I run powershell script using WMI CIM_DataFile, the first run I get the value of 2032127, but on second run I get the value of 18809343; on the third run I get the 1st value.

Is this a know issue, or is this the expected behavior?

VBscript was very reliable and consistent, when we deployed to Windows Server 2008R2 and Windows Server 2012, some of the items we were using in vbscript were no longer available, and found it easier to re-write the software in powershell, than re-write the vbscript code.  Our only problem, is the AccessMask property doesn't seem to be consistent when accessing it via powershell.

We are using AccessMask in combination with other properties to generate a software baseline inventory to be used to validate the integrity of the OS and Application Software.

Environment - All Virtual using VMware vSphere 5.1

Windows Server 2003 (32bit), Windows Server 2008 R2, WIndows Server 2012

Powershell v2.0

SQL Server 2005 SP4,

SQL Server 2008 R2 SP2

Any assistance would be appreciated.

DJ

Help with for loop and remove-item command

$
0
0

Hi all here is the code so far

$a = Get-Content C:\Users\cody-horton\Desktop\test.txt

for($i=0;$i -lt $a.Length;$i++){
    #$temp = [int32]::Parse($a[$i])

    Remove-Item '\\ceit2551202x0'$a[$i]'\C$\Program Files\MATLAB\R2013a\*' -Force
}

I have a text file with a few number in it that i want to get. They are in the array $a but I'm getting an error that says a positional parameter cannot be found that accepts argument '53' (it does this for all the numbers in the array.) I know in java you could have something like this   string + int + string. 

I'm not sure what to do I also tried to parse it with no luck. Thanks any help is appreciated.

Generate a hidden password

$
0
0

Hi,

I need to create a script that creates a zip file and creates a password on the zip file.  Because each zip file needs a different password I need a reliable way to create the password but a way to know what the password will be.

I was thinking that maybe I could do it with a date stamp which is then hashed.

Is there any standard for doing this?, I could easily do this with a variable and some maths functions but need to know its secure.

regards

james


Alter De Ruine

Viewing all 21975 articles
Browse latest View live


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