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

determine 32 or 64bit OS?

$
0
0

Hello,

Need to determine via script if running on a 32 or 64bit version of windows. It needs to work on server 2003, 2008, and 2008R2, so Win32_Operatingsystem's OSArchitecture property will not work for all (not available on server 2003).

I've seen others say to use the following (copy/paste from MSDN doc)
http://msdn.microsoft.com/en-us/library/aa394373%28v=VS.85%29.aspx : 

--------------------------
The Win32_Processor class has these properties.

AddressWidth
Data type: uint16
Access type: Read-only

On a 32-bit operating system, the value is 32 and on a 64-bit operating system it is 64. This property is inherited from CIM_Processor.

------------

so considering that is a property of the processor, I'm wondering if this can be relied on to determine the OS architecture? Can anyone confirm this is the recommended and reliable way to go? Otherwise, I will write a function that uses OSArchitecture for 2008 and 2008R2 and use the Win32_OperatingSystem 'Name' property for server 2003. Between those two things I know I can reliable return the correct information, but if there is one simple place to check, of course I would rather just do that.

anyone?


Filter can't handle object properties

$
0
0

Hi.

I've just been struggling a bit with the Get-Mailbox cmdlet and been wondering if this is a general issue with filters in Powershell and why that even happens.

Import-Module ActiveDirectory | Out-Null
Add-PSSnapin "Microsoft.Exchange.Management.PowerShell.SnapIn"
$MyObject = ConvertFrom-JSON "{ Plan: '10GB', UPN: 'anzu@an.dev' }"
Get-Mailbox -Filter { CustomAttribute3 -eq $MyObject.Plan }

Now this actually gives me mailboxes which have CustomAttribute3 as $null.

Comparing it with the Get-ADUser cmdlet it becomes a bit more clear:
get-aduser -filter { UserPrincipalName -eq $MyObject.UPN }
get-aduser : Property: 'UPN' not found in object of type: 'System.Management.Automation.PSCustomObject'.

What also doesn't work is:
Get-ADUser -Filter { UserPrincipalName -eq "$($MyObject.UPN)" }

What of course works is just giving it a string property

$UPN = $MyObject.UPN;
Get-ADUser -Filter { UserPrincipalName -eq $UPN }

It doesn't appear to be a scriptblock issue either as I can run:
$myobject = ConvertFrom-json "{ Prop:'hihihi' }"
$scriptblock = { "hi $($myobject.prop)" }
& $scriptblock
Output: hi hihihi

Or just: 
$scriptblockt ={ $myobject.prop }
& $scriptblockt
Output: hihihi

Someone can direct me to why this happens?

Powershell last update installed on computer

$
0
0

Hi,

I would like to find last date where an update was installed on a computer.

When I use get-hotfix date is not always shown...

Is there only wmic qfe to see it ? Because this is not powershell command and whith wmic updates are not ordered by installation date.

This query seems really complex to do as command line...

Maybe someone already have solution ?


Merci de marquer comme reponses les interventions qui vous ont ete utile.

Extract substring

$
0
0

I am trying to extract the country code from a list like below which is in a text file:

lab.local/2003Servers/US/server123
lab.local/Servers/AU/server1

$file= Get-Content .\list.txt
foreach ( $i in $file)
{
}
How can I get the second index of /. Once I get the second index of / I can extract two characters after it using substring?



Editing subsection of text in visio via powershell

$
0
0

I'm wondering if this i even possible

Currently I have a script to create a visio drawing relevant portions of the text being used are:

$application = New-Object -ComObject Visio.Application
$application.visible = $false
$documents = $application.Documents
$document = $documents.Add(“Basic Diagram.vst”)
$pages = $application.ActiveDocument.Pages
$page = $pages.Item(1)   
New-Variable -Name FolderTextBox$PNumber -Value $page.DrawRectangle($x-0.5, $y-0.25,$x+0.5,$y-0.7)
    (Get-Variable -Name FolderTextBox$PNumber).value.Text = ($accountslisted | Out-String).trim()
    (Get-Variable -Name FolderTextBox$PNumber).value.CellsU("LineColor").FormulaU = "RGB(255,255,255)"
    (Get-Variable -Name FolderTextBox$PNumber).value.CellsSRC(1,3,0).FormulaU = "RGB(255,255,255)"
    (Get-Variable -Name FolderTextBox$PNumber).value.Cells("Char.Color").FormulaU = "RGB(0, 0, 0)"
    (Get-Variable -Name FolderTextBox$PNumber).value.CellsU("Char.Size").FormulaU = "3 pt" 

A typical line of text being inputted could look like:
"R: Domain\ADGroup
M: Domain\ADGroup"

The "Char.Color" and "Char.Size" lines allow me to set colour and size of the font but what I'd really love to do is also modify the text to display like:
"R: Domain\ADGroup
M: Domain\ADGroup"

note the added bolding and underlining of the start of the lines.  everything I've read seems to show you can only affect the lines of text as a whole and not seek out a few characters within the text to modify it.  does anyone know if there is a way to do this via powershell

expanding the member list of a DL

$
0
0

I have this code that will get the members of the DL, however those DL with large member list it doesnt display all the members in the screen. I can use the switch "-expandproperty" but this would mean i have to remove the other columns on my select statement.. FOr this one I used PScustomobj in the hopes of displaying all its members but still its not listing all of its members. ANy suggestions?

Also when you use -ExpandProperty is there another way to list other columns in the select-object?

$data = Get-Content "adgrps.txt"
$server = "server name"
$ad_grp_arr = @()
$mem_arr = @()

foreach ($line in $data){ 
    $ad_grp_arr += Get-ADGroup -Server $server -Identity $line -Properties *
}

foreach ($mem in $ad_grp_arr){
   
    $ht = [PSCustomObject]@{
        DL_Name = $mem.Name
        #Members = $mem.Members -replace '^CN=|,.*$' -join ';'
        Members = $mem.Members -replace '^CN=|,.*$'
    }
    $mem_arr += $ht
}

$mem_arr


PoSH newbie, BaSH Oldie

Error handling issue

$
0
0

Hello,

I have a global misunderstanding about error handling. If I start some cmdlet that repeats some steps (classic pipeline for example) and one instance here drops an error but I want to ignore this error why cannot I do this:

    $error.Clear()
    Get-ChildItem ${env:ProgramFiles(x86)} -ErrorVariable $null -ErrorAction SilentlyContinue -Recurse | Where-Object {$_.Name -match "1.exe"} 
    $error[0]

The error always shows:

Get-ChildItem : Access to the path 'C:\Program Files (x86)\Google\CrashReports' is denied.
At line:2 char:5
+     Get-ChildItem ${env:ProgramFiles(x86)} -ErrorVariable $null -Erro ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Program File...le\CrashReports:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

Powershell Script for updating AD attributes on a set date

$
0
0

Hi,

Wondering if anyone is able to help - is there a way to script editing an AD user's job title but on a specific date?

For example change exampleuser's job title to examplejobtitle on 15th Nov

Thanks!


Running an excel macro from Powershell

$
0
0

Hello all!

I am trying to run an excel macro that's stored in a personal.xls file (in the XLSTART folder), in an automated script.  The problem is, I can run the macro when I put the commands in manually, but when thescript is running, I get: Exception calling "Run" with "31" argument(s): "'Personal.XLS' could not be found.

Here's the code for the macro section:

	$excel = new-object -comobject excel.application
	$workbook = $excel.workbooks.open("C:\test.xls")
	$worksheet = $workbook.worksheets.item(1)
	$excel.Run("Personal.XLS!FMT_PRICECHECKSTORE")
	$workbook.close()
	$excel.quit()
Thanks in advance for any assistance!

Script to delete after

$
0
0
I have got a script and it works ok but I want to add more command to empty the folder when all these tasks finished but not sure how as I tried to add Remove-Item -path 'E:\id\Upload\* it doesn't seem to work. Could someone please advise? param ( $localPath = "E:\id\Upload\*.*", $backupPath = "E:\id\Archive", $backupPath2 = "E:\id\Archive2", ) try { # Connect $session.Open($sessionOptions) # Upload files, collect results $transferResult = $session.PutFiles($localPath, $remotePath, $False, $transferOptions) # Iterate over every transfer foreach ($transfer in $transferResult.Transfers) { # Success or error? if ($transfer.Error -eq $Null) { Write-Output "$(Get-Date) Upload of $($transfer.FileName) succeeded, moving to backup">> $logFile # Upload succeeded, move source file to backup Move-Item $transfer.FileName $backupPath Move-Item $transfer.FileName $backupPath2 } } }

PowerShell Script: Export to csv file

$
0
0

OK, first of, a lot of y'all have been helping and guiding me with my first few PowerShell scripts and very thankful and grateful for all of the help. Still learning, of course.

Now, more process and script command learning needed.

I started this and everything worked with the exception of the last export to the second csv file. Now, it would be awesome if y'all can point me to right process to get all that into one csv and not 2 separate ones. :)

Objective: to check and export current registry value and then to set the item property - value and then export the changed value into csv file for verification and confirmation purposes.

Challenge (Problem): empty csv file after registry key value updated/ changed

what I have...

#Get computers from text file. 1 compute per line
$myComputerList = Get-Content C:\LocalFiles\TEST\ModifyRegistryValue\computerList.txt

#Loop Through Array
ForEach ($computer in $myComputerList) {

#Execute a command on the computer
Invoke-Command -ComputerName $computer -ScriptBlock {

#Verify current IM Provider Value for each machine and export it to csv file
Get-ItemProperty -Path "HKCU:\Software\IM Providers\" |
    Select-Object DefaultIMApp
  } | export-csv C:\LocalFiles\TEST\ModifyRegistryValue\CurrentRegValue.csv
}

Start-Sleep -s 10

#Get computers from text file. 1 computer per line
$myComputerList = Get-Content C:\LocalFiles\TEST\ModifyRegistryValue\computerList.txt

#Loop Through Array
ForEach ($computer in $myComputerList) {

#Execute a command on the computer
Invoke-Command -ComputerName $computer -ScriptBlock {

#The this command is to change the registry value for each machine and export to CSV file.
    Set-ItemProperty -Path "HKCU:\Software\IM Providers\" -Name "DefaultIMApp" -Value "Lync"} | export-csv -Path C:\LocalFiles\TEST\ModifyRegistryValue\UpdatedRegValue.csv
}

Like I've mentioned, I've gotten everything to work, just the way I wanted it, but the last piece is what I am struggling with. It creates the UpdatedRegValue.csv csv file but no information in the csv file - empty file.

It may be extremely simple for well-versed dynamic folks like y'all but for this newbie? LOL


TX



Using MS-Edge to replace IE11

$
0
0

I has been using Powershell 5 to work and manage webpages by something like below. Because IE seems being out of date. I am wondering if I can use MS-Edge instead. Does new version of Powershell has abilities to do that? Thanks

$ie = New-Object -com "InternetExplorer.Application"
$ie.Top = 1
$ie.Left = 3840
$ie.Width = 900
$ie.Height = 900
$ie.visible = $true

$ie.Navigate("https://www.google.com")

$a = $ie.document.getElementsByTagName('a')

IP subnet sort and rearrange in CSV file using powershell

$
0
0

I am trying to create a new CSV "Vlan_CSV" from the below "Source_CSV". I tried multiple Powershell examples and failed to achieve the goal. Any help on this will be appreciated. I can't find a way to post this in the request section. 

Source_CSV

Location Address vlan_ID vlan_Name vlan_IP vlan_SM
Location01 Address1 99 Main 10.1.1.1 255.255.255.0
Location01 Address1 40 WiFi 10.5.1.1 255.255.255.128
Location01 Address1 50 Server 10.3.1.1 255.255.255.0
Location02 Address2 99 Main 10.6.1.1 255.255.255.0
Location02 Address2 45 GuestWiFi 10.6.2.1 255.255.255.128
Location02 Address2 50 Server 10.8.1.1 255.255.255.128
Location03 Address3 99 Main 10.9.1.1 255.255.255.0
Location03 Address3 40 WiFi 10.9.1.1 255.255.255.0
Location03 Address3 45 GuestWiFi 10.9.1.1 255.255.255.0
Location03 Address3 50 Server 10.11.1.1 255.255.255.0


Desired output is below - "Vlan_CSV"

Location address vlan_99_IP vlan_SM_99 vlan_40_IP vlan_SM_40 vlan_45_IP vlan_SM_45 vlan_50_IP vlan_SM_50
Location01 Address1 10.1.1.1 255.255.255.0 10.5.1.1 255.255.255.128
10.3.1.1.255.255.255.0
Location02 Address2 10.6.1.1 255.255.255.0 10.8.1.1 255.255.255.128
Location03 Address3 10.9.1.1 255.255.255.0 10.11.1.1 255.255.255.0

Same desired result in another format to avoid display issues.

Location,address,vlan_99_IP,vlan_SM_99,vlan_40_IP,vlan_SM_40,vlan_45_IP,vlan_SM_45,vlan_50_IP,vlan_SM_50
Location01,Address1,10.1.1.1,255.255.255.0,10.5.1.1,255.255.255.128,,,10.3.1.1.255.255.255.0    
Location02,Address2,10.6.1.1,255.255.255.0,,,,10.8.1.1,255.255.255.128       
Location03,Address3,10.9.1.1,255.255.255.0,,,,10.11.1.1,255.255.255.0

No GuestWIFI at location1
No WiFi vlan and skipping GuestWiFi vlan at location02 because the second octet is same as the Main(99) vlan second octet for this location02
Skipped WiFI and GuestWiFi at location03 because the second octet is the same as the Main(99) vlan second octet for this location03.

This is the script I tried and not sure how to bring them in one row for each location. 


Write-Host "Creating the unique locations with Management, Wireless, Guest, Admin vlans, and Subnet Masks."

$Results = @()
$FilePath = "C:\temp\VLAN_Information_2.csv"
$CSV = Import-CSV $FilePath
ForEach ($item in $CSV) {

    If ($item.VLAN_ID -eq "99" -or $item.vlan_Name -match "Main") {
        $FacilityID=$item.Location
        Write-host "MGMT vlan IP " $item."vlan_IP"
        $Oct2=([ipaddress] $item."vlan_IP").GetAddressBytes()[1]
        }

    If ($Facility -ne "" ){

            If ($item.'VLAN_ID' -eq "40" -or $item.vlan_Name -match "WiFi"){
                $WiFi=$item."vlan_IP"
                $WiFiSM=$item.'vlan_SM'
                }
            If ($item.VLAN_ID -eq "99" -or $item.vlan_Name -match "Main") {
                $Main=$item."vlan_IP"
                $Main_SM=$item.vlan_SM
                }

            If ($item.VLAN_ID -eq "45" -or $item.vlan_Name -match "GuestWiFi"){
                $GuestWiFi=$item."vlan_IP"
                $GuestWiFi_SM=$item.vlan_SM
                }

            $details = [ordered]@{
                FacilityID=$Facility
                Facility_Name=$Facility
                Main=$Main
                Main_SM=$Main_SM
                WiFi=$WiFi
                WiFi_SM=$WiFi_SM
                GuestWiFi=$GuestWiFi
                GuestWiFi_SM=$GuestWiFi_SM
                            
                }
                $Results += New-Object psobject -Property $details
                } 
$Results | Export-Csv -Path C:\Temp\unique_Subnets.csv -NoTypeInformation

 

string parameter

$
0
0

I have a powershell script with parameters like below:

[parameter (Mandatory=$False)]
[string]$myfileShare='\\myfileshare.myorg.org\Dev\projects',

It gives an error:

The assignment expression is not valid...

what could be wrong?

Thanks


Thanks

copy not done

$
0
0

I have a powershell script, that at a final step to copy a file from one directory to another.

The permission should have no problem.

But the file is not copied.

if ($usemyShare) {
write-host "$(get-date -f G) - Copying $outputFilePath\$outputFileName to $SharePath"
try {
copy-item -path "$outputFilePath\$outputFileName" -Destination "$SharePath"
}
catch {
            write-host "$(get-date -f G) - ERROR while trying to copy file"
            $error[0]
}

what could be wrong?


Thanks


Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Management.Automation.SwitchParameter".

$
0
0

I am having an issue when running a swtich option in my script.

I am trying to take group the batchID results and then combine the unique names and join them

If ($CSV) {
    $MBX = Get-CSVFile
    $MigUsers = $MBX.emailaddress | Get-MigrationuserStatistics | 
    select identity,batchid,status,statusdetail,@{label='ErrorSummary';Expression={$_.errorsummary.split('>')[0]}},percentagecomplete,bytestransferred

    $batch = $migusers.batchid.name | group-object | Select-Object -Unique -ExpandProperty name
    $batchname = $batch -join ", "
    }

But I keep receiving the error :

Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"System.Management.Automation.SwitchParameter".
At D:\MigReport-V2.1.ps1:54 char:5
+     $batch = $migusers.batchid.name | group-object | Select-Object -U ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : ConvertToFinalInvalidCastException


vNext Work Around for Second Hop Issue on NonDomain Machines

$
0
0

I've asked the Microsoft Developer Community this question but I haven't had much success.

I am trying to create some automation tests with a vNext Build Definition in which the build agent RemotePSSession into a non-domain virtual machine (the test machine) and runs a batch file that can take several arguments. This batch file may read (installer files) or write (reports) to a network share that is on the domain. The issue that I am coming across is the second hop issue. Here is an article about it: https://blogs.technet.microsoft.com/ashleymcglone/2016/08/30/powershell-remoting-kerberos-double-hop-solved-securely/

In my instance, the PowerShell Remote Session is not able to pass the credentials we have authenticated previously in the test machine to access the network share’s resources. We have tried using CredSSP authentication on both the agent and the test machine to enable access but that has failed. The Net Use and other commands which call domain resources have also failed. We’ve even tried modifying the custom task PowerShell on Target Machines task and did not have much luck with it.

From what we have discovered is that there is no way to access the domain network shares with RemotePSSession with the following topology: Server A (which is in the domain or workgroup) ⇒ RemotePSSession + CredSSP into Server B (which is non-domain), using a local admin Server B account ⇒ Calls the network shares, with Net Use using some domain account.

It seems that the second hop only works for domain-joined machines (we have been testing it CredSSP using as well).

Let us know if there is a solution or workaround that we can implement.

Their response was >> If you can make sure the method is correct and the issue is caused by DevOps, we will be happy to help you with your issues about DevOps. Here are some documents might be helpful: https://docs.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-6.

I've looked at this documentation before and I haven't had much success, does anyone else have any suggestions?

Add-Group Members to diffrents groups Using a .CSV file

$
0
0

Good evening guys, so i already migrate the groups from domainA to domainB, just the groups since users are new in domainB and they cant be migrated, now i need to fix the membership on this grups but somehow is not working.

this is the script i have:

$Members = Get-Content -path 'C:\export\Csvfilename.csv'`

                                      -header GroupName,Members

foreach ($member in $members)

{Add-Groupmember -id $member.GroupName -members $member.members}

#NOte, $Member.Members is coming out with more than one user, and i dont know how to make this go thru, if i type user1,user2,user3 they get added to the group but if i put these three users in one variable they dont#

Please help.

Thanks.

Get adusers UPN

$
0
0

Anyone can suggest a one liner or script to get AD users that do not have UPN and email address matching? For example I have  mostly users with first.last@domain.com UPNs, but some are just just first name letter and surname@domain.com.

Thank you.


MK

Need to rename files based on specific string within the current name

$
0
0

I have a large list of image files that look like:

78103OW-1-newcolor.jpg 

78103OW-1-sandind.jpg 

78103OW-2-sandind.jpg 

78103OW-3-sandind.jpg 

I want to move the color to the front of the string (and remove from the end).  Is there an easy way to do this?

I was initially thinking to move each individual color doing something like:

Get-ChildItem -Filter"*-sandind" | Rename-Item -NewName {"sandind" + $_.Name.Substring(0,$_.BaseName.length-8) + $_.Extension}

But that doesn't work either - nothing happens.

Any help would be appreciated!!

Viewing all 21975 articles
Browse latest View live


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