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

Installing Windows6.1-KB2506143-x86.msu breaking psremoting

$
0
0

So we use powershell for everything and under 2.0 all is good all setup via GPO. However if we install that patch it breaks our remote management.

I am just looking for ideas on why?


Using PowerShell to download all security updates to a folder

$
0
0
Hi Gang,

We are looking for a way to use PowerShell to download all security updates to a folder so we can use this for our image build.

Has anyone done this before and has a solution they can share (or at the very least point me to a sample script)?

Thanks

PowerShell Script to find all instances of a named folder and delete all files older than 30 days

$
0
0

I am barely a beginner to scripting and PowerShell but I need to come up with a script that I can schedule to run on the a file server weekly.

I need a script will find all "Example_Data" folders within path "D:\" that are a sub folder of "My Documents" and delete all files within the "Example_Data" folder and any sub folder older than 30 days.


jst3751

How do I take selected part of string?

$
0
0

$string = "filename:pizza.jpg/"

I want to end up with "pizza.jpg".  I know the colon and / will always be there.  If not, for any reason, I need to capture it came back not as expected.

Disable bluetooth device

$
0
0

Hi,

Is it possible to disable bluetooth module in device manager without loading additional module on Powershell?

I' ve found something like that

$bluetooth = Get-wmiobject Win32_PnPEntity | where {$_.Caption -like "*bluetooth*" }
$bluetooth.Disable()
Start-Sleep -s 5
$bluetooth.Enable()
read-host

but there is no disable method :/

Thanks,

Hunal


How to read a text file and split data into separate files

$
0
0

Hello,

I have a text file with the following move-clustergroup data:

Move-ClusterGroup "SCVMM VM1 Resources" -Node HOST1
Move-ClusterGroup "SCVMM VM2 Resources" -Node HOST1
Move-ClusterGroup "SCVMM VM3 Resources" -Node HOST1
Move-ClusterGroup "SCVMM VM4 Resources" -Node HOST2
Move-ClusterGroup "SCVMM VM5 Resources" -Node HOST2
Move-ClusterGroup "SCVMM VM6 Resources" -Node HOST2

I'd like to split this file into two files by HOST.  So file 1 would have:

Move-ClusterGroup "SCVMM VM1 Resources" -Node HOST1
Move-ClusterGroup "SCVMM VM2 Resources" -Node HOST1
Move-ClusterGroup "SCVMM VM3 Resources" -Node HOST1

And file 2 would have:

Move-ClusterGroup "SCVMM VM4 Resources" -Node HOST2
Move-ClusterGroup "SCVMM VM5 Resources" -Node HOST2
Move-ClusterGroup "SCVMM VM6 Resources" -Node HOST2

I have the following script that partly does what I need:

Select-String "HOST1" -path C:\apps\Powershell_Scripts\ClusterGroup_scripts\test.txt -AllMatches -simplematch

The above script will give the following results:

test.txt:1:Move-ClusterGroup "SCVMM VM1 Resources" -Node HOST1
test.txt:2:Move-ClusterGroup "SCVMM VM2 Resources" -Node HOST1
test.txt:3:Move-ClusterGroup "SCVMM VM3 Resources" -Node HOST1

Almost there..I need to show just the exact lines like were in my file and not the name of the file...therefore remove the following "test.txt:1:"

Also, what is the instruction to write this out to a new text file?

Thanks in advance for any advice you can provide.




Having Trouble Passing Parameters to PS 2.0 script

$
0
0

I am very new to PowerShell and I am trying to write a script to help our analysts add servers to the domain. I am running PS2.0 on Win7. This script works like a charm when I write in static values for the variables. It breaks when I try to make it accept parameters. Here's the line I try to run in PS ISE (running as administrator):

.\OUComputerIntegrated.ps1 -strComputerName 'Monkey' -strOUName 'Primates'

I get the following error:

The term 'param' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\CCEADRevamp\OUComputerIntegrated.ps1:3 char:6

etc, etc [...]

Here's my script (I substituted in <name> for any identifying names... just know they are right):

Param([string]$strComputerName,[string]$strOUName)
Import-Module ActiveDirectory
Clear

$Path = "OU=" + $strOUName + ",OU=<name>,dc=<name>,dc=<name>"
try
{
    if (!([adsi]::Exists("LDAP://$Path")))
    {
        $objDomain = [ADSI]"LDAP://ou=<name>,dc=<name>,dc=<name>"
        $objOU = $objDomain.Create("OrganizationalUnit", "ou=" + $strOUName)
        $objOU.SetInfo()
        New-ADComputer -Name $strComputerName -SAMAccountName $strComputerName -Path "OU=$strOUName, OU=<name>, DC=<name>, DC=<name>"
        Write-Host "OU "$strOUName" Has Been Created. Computer "$strComputerName" was created in OU "$strOUName"."
    }
    else
    {
         Write-Host "OU "$strOUName" Already Exists"
         try
         {
            New-ADComputer -Name $strComputerName -SAMAccountName $strComputerName -Path "OU=$strOUName, OU=<name>, DC=<name>, DC=<name>"
            Write-Host "Computer "$strComputerName" Has Been Created in OU "$strOUName"."
         }
         catch
         {
            Throw("There was an error. The computer object was not created.")
         }
    }
}
catch
{
    Throw("There was an error. Neither the OU nor the computer object was created.")
}



looking to get volume stats on cluster storage via PS

$
0
0

I have a disk in the cluster (NOT a CSV) called 'share'

I can run get-clusterresource share and it returns

PS C:\Users\blake> get-clusterresource share

Name                          State                         Group                         ResourceType
----                          -----                         -----                         ------------
Share                         Online                        storagecloud                  Physical Disk

Is there any way I can further drill down and get any stats from that volume?  It is shared between two cluster nodes (HA file share) and I'd like to query the cluster directly rather than hitting up both nodes and using WMI to get the size, etc.

I know there is a parameter called 'diskvolumeinfo' because I can do this:

PS C:\Users\blake> get-clusterresource share | get-clusterparameter diskvolumeinfo

Object                        Name                          Value                         Type
------                        ----                          -----                         ----
Share                         DiskVolumeInfo                {1, 0, 0, 0...}               ByteArray

Feedback welcome!  And thanks!


Date Modified with increment of 1 for a hole year of files

$
0
0

Hi,

I have a folder called 2013 that contains about 20 folders, each containing rar files for each day of the year so far.  They are backups but I've discovered that some days the backups didn't complete so he file isn't there and I'd like a script to find the missing files

The way I see it I have 2 choices, first as the file names are in this format 130528.rar (YYMMDD) with some logic I could find any missing.  Secondly the date modified, so if I check the first file and it's date modified is 28/05/2013 I could compare this to the next date which is incemented by 1 to 29/05/2013

Something like this

$files = get-childitem -recurse c:\files

foreach ($Folder in $files) {

$latest = get-childitem $folder | Where {!$_.PsIsContainer}|select Name,DirctoryName, LastWriteTime |Sort LastWriteTime -descending | select -first 1}

Now I have the last modified file in a folder I need to see if the next olders file modified date exists and if not then write the offending file to a file

Anyone got any ideas?


Alter De Ruine


Why WebClient DownloadComplete Event is not executed

$
0
0

$webClient = New-Object System.Net.WebClient
    $Global:downloadComplete = $False
    Register-ObjectEvent $webclient DownloadFileCompleted `
      -SourceIdentifier WebClient.DownloadFileComplete `
      -Action {$Global:downloadComplete = $true}
    $source="http://XXXX\1.zip"
    "Source Address is {0}  " -f $source
    $dest = "C:\windows.zip
    $webClient.DownloadFile($source,$dest)

   "the value of downloadComplete is {0}" -f $downloadComplete

why the DownloadComplete Event is not executed value of the download complete is still "Failse" ?


Best Regards, Mike

Simple Question (I hope) for ScheduledJob

$
0
0

Hello All,

I am trying to teach myself Powershell and currently, I am trying to make a script to run a ScheduledJob to backup a local folder onto a network share.

I finally found out why my script wasn't running and that's because of an option within taskschd.msc that has "Do not store password. The Task will only have access to local resources" checked on my script.

Is there a way to uncheck this automatically using New-ScheduledJobOption (or any other way)?  

Thanks!

Please clarify referencing System.Uri assembly.

$
0
0

I've been learning some C# and using PowerShell a lot lately, but something in PowerShell isn't working out for me, and I cannot find the MS doc that explains to me why.

Please help right quick:

In my PowerShell ISE session, I want to use System.Uri.

In my code, it worked when I specifically said [System.Uri]::method but I wanted something like "using" in C#.  Even after "import-module -name System.Uri" (which worked, assuming that's correct) I still don't have the desire effect of Uri being recognized.

Any tips? 

Assistance with Get-content to parse data from one file to create many files - out-file limited to 20 records per file

$
0
0

Hello,

I've received help on my script to read a large file and using Get-Content and Select-String to create multiple files.  My script works like a charm and looks like this:

$input = ".\Move_ClusterGroup_script.txt"

#Create "A" Hosts move scripts.

gc $input | select-string "HOSTA01" | out-file .\HOSTA01.txt
gc $input | select-string "HOSTA02" | out-file .\HOSTA02.txt
gc $input | select-string "HOSTA03" | out-file .\HOSTA03.txt
gc $input | select-string "HOSTA04" | out-file .\HOSTA04.txt
gc $input | select-string "HOSTA05" | out-file .\HOSTA05.txt


#Create "B" Hosts move scripts.
gc $input | select-string "HOSTB01" | out-file .\HOSTB01.txt
gc $input | select-string "HOSTB02" | out-file .\HOSTB02.txt
gc $input | select-string "HOSTB03" | out-file .\HOSTB03.txt
gc $input | select-string "HOSTB04" | out-file .\HOSTB04.txt
gc $input | select-string "HOSTB05" | out-file .\HOSTB05.txt

I'd like to expand on this script with the following requirement:

I'd like to write out at a maximum 20 records per file.  When 20 are reached a new file will be created until all Select-String variables are satisified.  So this would mean that my out-file would need to change and I would see out-file records like .\HostB01_1.txt, .\HostB01_2.txt, .\HostB01_3.txt...etc or something similar that satisify's the requirement.

Thank you.


Compressing Log Files from Multiple Sources?

$
0
0

I need some help with a problem I'm facing at work. I've been tasked with developing a script to take video files older than a day stored from multiple directories and placing them in zipped folders named after their parent directory.

For example, I would need to search for all files in C:\DirA and move them to C:\ Archive\DirA(date-1).zip I would then need the script to go to C:\DirB and move them to C:\ArchiveDirB(date-1).zip and so on. 

I'm really lost and I don't have much of an idea on how to tackle this one. I have a partial script from another discussion thread that is running into errors with the actual zip process. Any help would be greatly appreciated.

Here is the actual code I'm trying to use. This code lacks the needed parts for moving the individual parts from the subfolders and doesn't quite work...

#usage: creat new zip function
function New-Zip
{
	param([string]$zipfilename)
	set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
	(dir $zipfilename).IsReadOnly = $false
}

#usage: -Recurse | add-Zip
function Add-Zip
{
	param([string]$zipfilename)

	if(-not (test-path($zipfilename)))
	{
		set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
		(dir $zipfilename).IsReadOnly = $false	
	}
	$shellApplication = new-object -com shell.application
	$zipPackage = $shellApplication.NameSpace($zipfilename)
	foreach($file in $input) 
	{ 
            $zipPackage.CopyHere($file.FullName)
            Start-sleep -milliseconds 500
	}
}

#Change these variables to meet needed reqs

$targetFolder = 'D:\sample'
$destinationFolder = 'C:\sample'
$now = Get-Date
$days = 1
$lastWrite = $now.AddDays(-$days)

#usage: destination folder

Get-ChildItem $targetFolder -Recurse | Where-Object { $_ -is [System.IO.FileInfo] } | ForEach-Object {
	If ($_.LastWriteTime -lt $lastWrite)
	{
		$_ | New-Zip $($destinationFolder + $_.BaseName + $lastWrite + ".zip") 
		$_ | Add-Zip $($destinationFolder + $_.BaseName + $lastWrite + ".zip")
	}
}

Format result of AddDays?

$
0
0

This command does what I am seeking:   get-date -f "yyyyMMdd"

However, I want it for the previous day:   (get-date).AddDays(-1)

...but I cannot figure out how to format it after AddDays.

Incorrect:  (get-date -f "yyyyMMdd").AddDays(-1)


Dynamic menu construction ($Host.UI.PromptForChoice)

$
0
0

Hi guys,

here I am (again!) and I need some help (again!!)

What I am trying to do:

- Get the list of IP address on localhost

- Use that list to build a menu where each IP address is a menu option

- When the user choose one option, get the selected IP address in a variable for further use.

Where am I:

$TestIP=Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DefaultIpGateway} | Select-Object -ExpandProperty IPAddress
$arguments=@()
$CountIP=$TestIP.Count
$rootfolder=1..$CountIP
$title="Website binding IP Address selection" 
$message="Please select an IP address for the website you're about to create." 
$arguments+=$Cancel=New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel", ` "Cancels and exits the script." 
$i=0 
ForEach($IP in $TestIP) 
{ 
$i++
$arguments+=New-Object System.Management.Automation.Host.ChoiceDescription "`&$i $IP", ` "Select $IP for the website to create." 
} 
$options=[System.Management.Automation.Host.ChoiceDescription[]]$arguments
$result=$Host.UI.PromptForChoice($title, $message, $options, 0)

But that doesn't work... The menu is buit, but first I don't know why I get an extra (unwanted) $i in front of each IP address:

[C] Cancel  [1] 1 xxx.xxx.xxx.xxx  [2] 2 xxx.xxx.xxx.xxx  [?] Help

And I can't figure out how to get the chosen IP address after the user has select it...

Powershell script to compare AD UserObject Group Memberships in Excel

$
0
0

Greetings, Venerable Ones,

Lots of organizations use Global Security Groups.  I have been working on a script that gets a list of users, lists all of their groups, and then creates a matrix in excel to display which groups each of the user objects is a member of.  It is quite handy when trying to decipher how objects differ from one another.  I am running into an issue though that I was hoping you might be able to help me with.  After the script completes creating the matrix, (because I am too lazy to do it via the gui), I want Powershell to autosum both the Columns and Rows so that when my downline techs run the script, they can see how many users are members of each group, and how many groups each user is a member of.

I think the problem that I am running into is that in trying to variable-ize the excel range, the ":" character is not recognized as a delimiter, but rather as part of the variable ( as in $env:username ), and I am not "gettin' jiggy" with VBA vs. Powershell.  Could you shine a light on this, and help me with the xlSum function?  The state in which it is in right now only handles the logic for one axis, and I admit, ashamedly, that it does not work...  Perhaps you could reveal some magical way to do all of this in only 14 lines that would make me feel way totally inadequate too?  Powershell Gurus, can you help me land this plane???

#CompareUserGroupMembershipsFromList.ps1
#[string](0..9|%{[char][int](32+("45737569004673677976").substring(($_*2),2))})-replace "\s{1}\b"
# save list.txt file in same directory as script with LogonNames (one per line) example follows:

#CarlHungus
#nio
#morpheus
#spock

cls
$erroractionpreference = "SilentlyContinue"
Import-Module ActiveDirectory
$currentfolder = split-path $myinvocation.mycommand.path
$groups = ""
$userlist = GC $currentfolder\list.txt | sort
if (test-path $currentfolder\temp.txt) {remove-item $currentfolder\temp.txt}
if (test-path $currentfolder\MasterGroupList.txt) {remove-item $currentfolder\MasterGroupList.txt}
if (test-path $currentfolder\UserCNs.txt) {remove-item "$currentfolder\UserCNs.txt"}

Foreach ($user in $userlist)
    {
        $array = @() 
        $array2 = @() 
        $groups = Get-AdUser -Identity $user -property "MemberOf" 
        $sortedGroups = $groups.memberof | Sort | Get-Unique
            Foreach($group in $sortedGroups) 
            {$array +=$group} 
        $number = $array.count
        foreach ($item in $array)
        {      
         $1 = $item -replace "CN\=","" 
         $2 = $1 -replace "^*,OU\=.*$","" 
         $3 = $2 -replace "^*,Users.*$",""
         $4 = $3 -replace "^*,Builtin.*$",""
         add-content $currentfolder\temp.txt $4    
        }  
    }
$MasterGroupList = gc $currentfolder\temp.txt | sort | Get-Unique
remove-item $currentfolder\temp.txt
foreach ($schlub in $MasterGroupList) 
{add-content $currentfolder\MasterGroupList.txt $schlub}
# some Excel Constants 
# line styles 
$xlLineStyleNone = -4142 
$xlContinuous = 1 
$xlDash = -4115 
 
$a = New-Object -comobject Excel.Application
$a.Visible = $true
$functions = $a.WorkSheetfunction
$b = $a.Workbooks.Add()
$WS=$a.ActiveSheet
$cells = $WS.Cells
$date = Get-Date
#define some variables to control navigation
$row=1
$col=2
        $WS.UsedRange.Borders.LineStyle = $xlContinuous
        $blue = 255
        $green= 0
        $red = 0
        $a = 1
        $WS.UsedRange.Borders.Color = $a
        $WS.UsedRange.Borders.Weight = $xlThin
        $WS.Application.ActiveWindow.SplitColumn = 1
        $WS.Application.ActiveWindow.SplitRow = 1
        $WS.Application.ActiveWindow.FreezePanes=$true 
#insert column headings
GC $currentfolder\MasterGroupList.txt | foreach {
        $cells.item($row,$col)=$_
        $cells.item($row,$col).font.bold=$False
        $cells.item($row,$col).Orientation = 90
        $cells.EntireColumn.AutoFit() | Out-Null
        $WS.UsedRange.Borders.LineStyle = $xlContinuous
        $col++
    }
$row=2
$col=1
$blarb = Get-Content ("$currentfolder\list.txt") | Sort # 
foreach ($slarb in $blarb)
    {   
        $CN = Get-AdUser -filter 'SamAccountName -eq $slarb' 
        Add-Content "$currentfolder\UserCNs.txt" $CN
    }
$GroupList = @{} 
Function IsMember ($ADObject, $GroupName) 
    { 
        If ($GroupList.ContainsKey($ADObject.sAMAccountName.ToString() + "\") -eq $False) 
        { 
            $GroupList.Add($ADObject.sAMAccountName.ToString() + "\", $True) 
            $ADObject.psbase.RefreshCache("tokenGroups") 
            $SIDs = $ADObject.psbase.Properties.Item("tokenGroups") 
            ForEach ($Value In $SIDs) 
            { 
                $SID = New-Object System.Security.Principal.SecurityIdentifier $Value, 0 
                $Group = $SID.Translate([System.Security.Principal.NTAccount]) 
                $GroupList.Add($ADObject.sAMAccountName.ToString() + "\" + $Group.Value.Split("\")[1], $True) 
            } 
        } 
                If ($GroupList.ContainsKey($ADObject.sAMAccountName.ToString() + "\" + $GroupName)) {Return $True} 
                Else {Return $False } 
    } 
     $UserCNs = Get-Content("$currentfolder\UserCNs.txt") 
     foreach ($item in $UserCNs) 
        {  
            $User = [ADSI]"LDAP://$item" 
            $3 = $item -replace "CN\=","" 
            $4 = $3 -replace "^*,OU\=.*$",""
            $x=1
            $y=2
                   foreach ($habba in Get-content $currentfolder\MasterGroupList.txt)
                            {
                             If (IsMember $User $habba -eq $True) 
                                 {  write-host Yes,$habba,$User.sAMAccountName -Foregroundcolor green
                                    $cells.item($row,$col)=$4
                                    $cells.EntireColumn.AutoFit() | Out-Null
                                    $cells.item($row,$col).font.bold=$True
                                    $WS.Cells.Item($row,$y).Value() =1;$WS.Cells.Item($row,$y).Interior.ColorIndex = 34#;$WS.Cells.Item($row,$y).HorizontalAlignment = -4108
                                 }
                             Else
                                 {
                                    write-host No,$habba,$Computer.sAMAccountName -Foregroundcolor red
                                 }
                              $y++
                              $WS.UsedRange.Borders.LineStyle = $xlContinuous        
                            }
                   $Row++
         } 
if (test-path $currentfolder\MasterGroupList.txt) {remove-item $currentfolder\MasterGroupList.txt}
if (test-path $currentfolder\UserCNs.txt) {remove-item "$currentfolder\UserCNs.txt"}
  
  
  Function Convert-NumberToA1 
    { 

      Param([parameter(Mandatory=$true)] 
            [int]$number) 
 
      $a1Value = $null 
      While ($number -gt 0) { 
        $multiplier = [int][system.math]::Floor(($number / 26)) 
        $charNumber = $number - ($multiplier * 26) 
        If ($charNumber -eq 0) { $multiplier-- ; $charNumber = 26 } 
        $a1Value = [char]($charNumber + 64) + $a1Value 
        $number = $multiplier 
      } 
      Return $a1Value 
    }
#
 
Function xlSum 
        {
                $range = $WS.usedRange
                $rows  = $range.rows.count # Takes you to the last used row
                $cols   =  $range.columns.count # Takes you to the last used column
                $Sumrow = $rows + 1
                $Sumcol  = $cols + 1
                write-host row summary $Sumrow
                write-host column summary  $Sumcol
                $Q=2
                        do
                            {
                                write-host $Q
                                $Y=2
                                $p =  Convert-NumberToA1 ($Q)
                                $grid1 = "$p$Y".ToString()
                                $grid2 = "$p$rows".ToString()
                                $r = $WS.Range("'$grid1':'$grid2'") 
                                $WS.cells.item($p,$Sumrow) = $functions.sum($r)
                                [void]$range.entireColumn.Autofit()
                                $Q++
                             }
                    while ($Q -lt $rows)
        } # End Function
  xlSum 

 #End Script


get-aduser not finding user object

$
0
0

hello

Get-aduser not finding newly created user object created via ADUC. If I use new-user cmdlet to create the user I can turn around and fine the user Immediately.

I create a new user object 'Testuser' in aduc then run get-aduser testuser and it "returns: Get-ADUser : Cannot find an object with identity: 'testUser' under :DC=dev,DC=Local"

If I use new-ad user to create "testuser2"  then do the Get-Aduser everything works fine.

Exchange Powershell Export has stopped on sent Items folder

$
0
0
I'm trying to export a users mailbox to a PST file. The mailbox is around 9.6GB. It's been going along fine for the last 3 hours, but now it has stopped on 10867/16047 of the sent Items folder. What can I do about this?

Open a web browser and pass logon credentials

$
0
0

Hi,

I am trying to write a script to open a browser and login to a page that uses a username and password field .  It's not runing in IIS and the username and password are just on the form so I am unsure how I would pass the credentials in.  It's not basic authentication either.

I have this so far

   $url = "https://testURL
 
  
    $webclient = new-object System.Net.WebClient
     $credCache = new-object System.Net.CredentialCache
    
     $creds = new-object System.Net.NetworkCredential("username","password", "domain")
     $credCache.Add($url, "Negotiate", $creds)
     $webclient.Credentials = $credCache
 


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>