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

PowerShell script doesn't work in Task Scheduler in Windows Server 2016

$
0
0

1) I have seen a lot of topics like that, but don't find the solution.

I need to start powersheel script every 5 minutes from Administrator with highest privileges:

Action is 

Start program

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

-File "C:\Work\ConvertAndUpload.ps1"

In the history - task has been done. But I see that script have not been work. Screenshot from history:

2) As a second way to do this i have tried to create .bat file with start this powershell script and start this .bat from Task Scheduler. It doesn't work too (without errors, just ps-script not really starting).

3) I have tried to create new task from powershell console (to do from SYSTEM):

It is working without errors too, but still doesn't really do powersheel script.

Powershell script is very easy - it converts .xls file to .csv and send it ftp. Code of this script:

$source = 'C:\Work\Test'

Function ExcelCSV ($File)
{
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $false
    $Excel.DisplayAlerts = $false
    $wb = $Excel.Workbooks.Open($File.FullName)

foreach ($ws in $wb.Worksheets)
        {
        $ws.SaveAs(($Files.FullName -replace ".xls$","") + ".csv", 6)
        }
        $wb = $Excel.Workbooks.Close()
        $Excel.Quit()
}

 Foreach ($Files in (Get-ChildItem -Path $source -Filter "*.xls"))
{
    ExcelCSV($Files)
}
$FileToUpload = "C:\Work\Test\test.csv"
$ftp = 'ftp://login:password@ftpaddress:2225/test.csv'
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)

Please, help, I just don't know what to do more.

P.S. It is new account here, so I can't contain images in body, so I will try put them in comments.


PowerShell script doesn't work in Task Scheduler in Windows Server 2016

$
0
0

1) I have seen a lot of topics like that, but don't find the solution.

I need to start powersheel script every 5 minutes from Administrator with highest privileges:

Action is 

Start program

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

-File "C:\Work\ConvertAndUpload.ps1"

In the history - task has been done. But I see that script have not been work. Screenshot from history:

2) As a second way to do this i have tried to create .bat file with start this powershell script and start this .bat from Task Scheduler. It doesn't work too (without errors, just ps-script not really starting).

3) I have tried to create new task from powershell console (to do from SYSTEM):

It is working without errors too, but still doesn't really do powersheel script.

Powershell script is very easy - it converts .xls file to .csv and send it ftp. Code of this script:

$source = 'C:\Work\Test'

Function ExcelCSV ($File)
{
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $false
    $Excel.DisplayAlerts = $false
    $wb = $Excel.Workbooks.Open($File.FullName)

foreach ($ws in $wb.Worksheets)
        {
        $ws.SaveAs(($Files.FullName -replace ".xls$","") + ".csv", 6)
        }
        $wb = $Excel.Workbooks.Close()
        $Excel.Quit()
}

 Foreach ($Files in (Get-ChildItem -Path $source -Filter "*.xls"))
{
    ExcelCSV($Files)
}
$FileToUpload = "C:\Work\Test\test.csv"
$ftp = 'ftp://login:password@ftpaddress:2225/test.csv'
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)

$webclient.UploadFile($uri, $FileToUpload)

exit 0

Please, help, I just don't know what to do more.

P.S. It is new account here, so I can't contain images in body, so I will try put them in comments.


Recursive script to add Full control for Administrators?

$
0
0

Does anyone have a script that I can modify to change all the file and folder permissions on my primary (boot) storage device to give Administrator's Full control? It seems I cannot do it en masse but need to do a recursive loop through all files/folders, and for each, save the owner, take ownership, add Administrators:F, then finally restore original ownership. If there is an error, it should keep going.

I found "GET-ACL $CurrentFile | Select Owner" but I haven't seen how to extract just the owner from the several lines of text it puts out. It seems this script should only take a half dozen lines, however my inexperience makes me worry there will be problems that I cannot anticipate. For example I thought I had once found that the system sometimes gets angry if it doesn't find the expected owner for a file or folder (e.g., TrustedInstaller), but I've read many posts that imply this should not be the case.

Initialize-Disk : The disk has already been initialized.

$
0
0

Hello Everyone

I'm trying to create a bootable usb drive that supports UEFI boot windows 10

I used clear-disk command with -removeData , but the problem is that I need to initialize the USB drive as GPT I receive the following error when I type

$removabledrive = Get-WmiObject Win32_diskdrive | Where-Object interfacetype -EQ usb | Select-Object caption -ExpandProperty caption

Clear-Disk -FriendlyName $removabledrive -RemoveData

Initialize-Disk -FriendlyName $removabledrive –PartitionStyle GPT

any idea how can I do it gpt, my hole purpose is to make uefi bootable device using the mentioned script

thanks for all

Migration stuck at 95% using SPMT

$
0
0

failed to upload files to sharepoint using SPMT and migration stuck at 95%, We don't wanna restart the migration because some users was already used the documents in sharepoint online. It's a long process if we manually upload the 7,000 failed items to sharepoint online.

Is there any way to upload the failed items via powershell, import via csv?

I tried the following command as a test and got the error below.

PS C:\Users\xxxxxx> $mydata = import-csv V:\dataupload.csv
PS C:\Users\xxxxxx> $mydata

Source
------
V:\CloudSP\HR\great1.rtf
V:\CloudSP\HR\great2.rtf
V:\CloudSP\HR\great3.rtf
V:\CloudSP\HR\greatxls1.xlsx
V:\CloudSP\HR\greatxls2.xlsx
V:\CloudSP\HR\greatxls3.xlsx

PS C:\Users\xxxxxx> Add-PnPFile -Path $mydata -folder "/Shared Documents"
Add-PnPFile : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Path'. Specified method
is not supported.
At line:1 char:19
+ Add-PnPFile -Path $mydata -folder "/Shared Documents"
+                   ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Add-PnPFile], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,SharePointPnP.PowerShell.Commands.Files.AddFile

Hope you can help me on this.


Get-PhysicalDisk exception

$
0
0

I am running Windows 10 version 1903, clean install on a new PC.  I am completely new to PowerShell.   I was intending to use it to configure a tiered storage space, but failing at the first step.  Hoping someone can tell me what I'm doing wrong.

When I enter "Get-PhysicalDisk" on this machine, I get the following exception:

Exception calling "MoveNext" with "0" argument(s): "Invalid property "
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Storage\StorageScripts.psm1:2344 char:20
+             while ($enumerator.MoveNext())
+                    ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CimException

Can anyone tell me why this is failing?


Printing image using .net framework in powershell

$
0
0

I wrote this powershell script to print images. But when the script runs and starts to print I am getting empty page printout. I tried to use printdocument and graphics from .NET framework.This is my first time using powershell and .NET framework so I used these scripts for reference: script1script2. I don't know what I am missing here. Any help is greatly appreciated.

function Start-Print {

    $CopyCount = 1

    $pd = New-Object System.Drawing.Printing.PrintDocument

    $files = Get-ChildItem -Path "D:\Users\Phuntsho Wangdi\Desktop\New folder\unprinted\*" -Include "*.jpeg", "*.png", "*.jpg"

    foreach ($global:file in $files) {

        $file_name = Get-ChildItem -Name $file

        Write-Host $file_name

        $pd.DefaultPageSettings.PrinterSettings.PrinterName = "Canon E510 series printer"
        $pd.DefaultPageSettings.Landscape = $True
        $pd.PrinterSettings.Copies = $CopyCount
        $pd.DefaultPageSettings.Color = $false
        $pd.DocumentName = $file_name

        $action = {
            $bmp = New-Object System.Drawing.Bitmap("$file")

            #implemented from https://www.powershellgallery.com/packages/RoughDraft/0.1/Content/Send-Printer.ps1
            $newWidth = $bmp.Width * 100 / $bmp.HorizontalResolution
            $newHeight = $bmp.height * 100 / $bmp.VerticalResolution

            $widthFactor = $newWidth / $EventArgs.PageSettings.PrintableArea.height
            $HeightFactor = $newHeight / $EventArgs.PageSettings.PrintableArea.Width

            $widthMargin = 0
            $heightMargin = 0

            if ($widthFactor -ge 1 -or $HeightFactor -ge 1) {
                if ($widthFactor -gt $HeightFactor) {
                    $newWidth = $newWidth / $widthFactor 
                    $newHeight = $newHeight / $widthFactor 

                }
                else {
                    $newWidth = $newWidth / $HeightFactor
                    $newHeight = $newHeight / $HeightFactor

                }               
            }

            $heightMargin = (($EventArgs.PageSettings.PrintableArea.Height - $newHeight) / 2) / 2

            $EventArgs.Graphics.DrawImage($bmp, ($EventArgs.PageSetting.HardMarginX + $widthMargin), ($EventArgs.PageSetting.HardMarginY + $heightMargin), $newWidth, $newHeight)
        }

        $endprint = {
            $bmp.Dispose()
        }

        Register-ObjectEvent -InputObject $pd -EventName "PrintPage" -Action $action
        Register-ObjectEvent -InputObject $pd -EventName "EndPrint" -Action $endprint

        $pd.Print()
    }
    Write-Host "Done!"

Using variables for the arguments in the Grant-SMBShareAccess cmdlet

$
0
0

The variable for the share was evaluated but the value of the variable represented by the share permissions was not. Is there a way to evaluate its value?

 Grant-SmbShareAccess -Name $SHARE -AccessRight Read -AccountName $SHARERead
Grant-SmbShareAccess : Cannot validate argument on parameter 'Name'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At line:1 char:36+         Grant-SmbShareAccess -Name $SHARE -AccessRight Read -AccountN ...+                                    ~~~~~~+ CategoryInfo          : InvalidData: (:) [Grant-SmbShareAccess], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationError,Grant-SmbShareAccess



Using Powersell to remove apps and reinstall newer versions of the same app

$
0
0

Forgive the way my mind wanders I am trying to automate removed a variable number of apps and reinstall the newer version of the same apps from a lot of Windows 7/10 computers I am not even sure it is possible.

 

I have only used PowerShell this week so my skills are below newbie level in it

I have to visit about 300 workstations each of them will have between 1 and 20 programs named RED XXXX

I am trying to write/modify a script to do the following

Make a list of all application named “RED”

Uninstall all applications whose name starts with RED

Reinstall the new version of the Red Application

I found and slightly edited this script which gets a list of most of the application and saves it

# back up list of currently installed RED and save to C:\IT\Red.txt

$app= Get-WmiObjectWin32_Product| where { $_.name-like"*Red*" } | Out-Filec:\it\Red.txt

 But it is not 100% correct it misses a few so I found this script

If(!([Diagnostics.Process]::GetCurrentProcess(). Path -match ‘\\syswow64\\’)) {

$unistallPath = “\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\”

$unistallWow6432Path = “\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\”

@( if (Test-Path “HKLM:$unistallWow6432Path” ) { Get-ChildItem “HKLM:$unistallWow6432Path”} if (Test-Path “HKLM:$unistallPath” ) { Get-ChildItem “HKLM:$unistallPath” } if (Test-Path “HKCU:$unistallWow6432Path”) { Get-ChildItem “HKCU:$unistallWow6432Path”} if (Test-Path “HKCU:$unistallPath” ) { Get-ChildItem “HKCU:$unistallPath” } ) | ForEach-Object { Get-ItemProperty $_.PSPath } | Where-Object { $_.DisplayName -and !$_.SystemComponent -and !$_.ReleaseType -and !$_.ParentKeyName -and ($_.UninstallString -or $_.NoRemove) } | Sort-Object DisplayName | Select-Object DisplayName

}

else { -foregroundColor red

}  | Out-File C:\IT\red.txt

 

This one is accurate and complete but when I try to pipe the output I get an empty Pipe is not allowed error and it gives me all application not just the ones from Red

 

I need to combine the two, then I need to have the created file be the variable for the install part of the script

 

I found a new Script that also works

Get-Package -Provider Programs -IncludeWindowsInstaller -Name "Red*" | Out-File C:\it\Red.txt

This is the output

Red Apple           12.7.1501.2                                      Programs                                                                                                    

Red Sky                  12.4.20000.53                                    Programs                                                                                                    

Red Sand                 12.7.3031.3                                      Programs                                                                                                    

Red Planet               12.7.3030.2                                      Programs                                                                                                    

Red Carpet               12.7.1501.4                                      Programs

 

So I need to uninstall $red (pull list from c:\it\red.txt

Then I want to reinstall the newer version of the same programs

Like Install-Package –$red "K:\$red\red.exe" –force

But instead of using red I want powershell to use a variable and just reinstall the new versions of the same program it just deleted otherwise its 1hr per machine times about 300 machines.

The issue is each machine could have a different number or "Red" programs and or a different set of the 22 possible red programs. ie machine a1111 could have red moon but not red sky, A1112 could have red moon, red, sky, red sand, and a1113 could have all 22 Red programs installed.

 

Import Users from csv file

$
0
0

Hi, I try to import users by this script, but I get an error.

              

*****************************************************************

# Import active directory module for running AD cmdl

ets
Import-Module activedirectory

#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\Users\ezehtabchi\Desktop\Users\bulk_users2.csv -Delimiter ';'

#Loop through each row containing user details in the CSV file 
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below

$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou #This field refers to the OU the user account is to be created in
    $email      = $User.email
    $streetaddress = $User.streetaddress
    $city       = $User.city
    $zipcode    = $User.zipcode
    $state      = $User.state
    $country    = $User.country
    $telephone  = $User.telephone
    $jobtitle   = $User.jobtitle
    $company    = $User.company
    $department = $User.department
    $Password = $User.Password


#Check to see if the user already exists in AD
if (Get-ADUser -filter {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account

        #Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username@harvey-eug.local" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Lastname, $Firstname" `
            -Path $OU `
            -City $city `
            -Company $company `
            -State $state `
            -StreetAddress $streetaddress `
            -OfficePhone $telephone `
            -EmailAddress $email `
            -Title $jobtitle `
            -Department $department `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True

}
}






Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
At C:\Users\Administrator\Desktop\Users\bulk_users1.ps1:31 char:6
+     if (Get-ADUser -filter {SamAccountName -eq $Username})
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microso 
   ft.ActiveDirectory.Management.Commands.GetADUser

******************


Look for script to install/remove programs

$
0
0

Hi,

I need to remove program1 and program2 and install program3 and program4 on multiple PCs. I will use msiexec.exe to remove the program1,2. Program3 is exe installer, program4 is MSI installer. 

Requirement: need to remove program 2 after removing program1 is completed, then install program3, when program 3 installation is completed, install program4.

I have the command line ready and tested and they worked. Can someone help to put together to create a script or point me if there is a existing script out there?

Remove program1: msiexec.exe /x {7A4192A1-84C4-4E90-A31B-B4847CA8E23A} /qn

Remove program2: msiexec.exe /x {BCF4CF24-88AB-45E1-A6E6-40C8278A70C5} /qn

Install program3: program3.exe /i "c:\"

Install proram4: msiexec.exe /a "c:\program4.exe"

Thanks in advance!


Grace

Floating point arithmetic

$
0
0

I've (almost) always known that errors creep into the results of floating point calculations. Usually the errors are small, but they're still there. I had occasion to sum the contents of an array of double precision numbers and the results were, um, surprisingly inaccurate.

Here's an example (shortened, but representative) using Measure-Object. You'll get the same result if you simply add the numbers:

1.0, 1E+100, 1.0, -1E+100 | Measure-Object -Sum

Count    : 4
Average  : 
Sum      : 0
Maximum  : 
Minimum  : 
Property :

It's been decades (literally) since I've had to deal with this, but after digging a bit I found a (much slower) way to sum an array of double precision numbers:

function KleinSum{
    param(
        [double[]]$var
    )

     [Double] $s = 0.0
     [Double] $cs = 0.0
     [Double] $ccs = 0.0
     $var | foreach {
       [Double] $t = $s + $_
       if ($s -ge $_) {
         $c = ($s - $t) + $_
       }
       else{
         $c = ($_ - $t) + $s
       }
       $s = $t
       $t = $cs + $c
       if ($cs -ge $c){
         $cc = ($cs - $t) + $c
       }
       else{
         $cc = ($c - $t) + $cs
       }
       $cs = $t
       $ccs = $ccs + $cc
     }
     $s + $cs + $ccs
}

[double[]]$d = 1.0, 1E+100, 1.0, -1E100
KleinSum $d

# https://en.wikipedia.org/wiki/Kahan_summation_algorithm

Run the same set of numbers using that function and you get the correct result: 2.0.

This probably doesn't have much application in an automation language like Powershell, but maybe it'll help someone else.


--- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

Powershell script for data cleanup

$
0
0

Hi, 

I have a scenario where i have to clean the archived data older than 5 days. The path structure is like " Environment -> ApplicationName -> ServiceName -> Input/Output Folder -> Year -> Month -> Day -> files for that day"

I have created below script for this. 

$StartFolder = "Folder Path is provided here"
$deletefilesolderthan="5"

#Get Foldernames for ForEach Loop
$SubFolders = get-childitem -path $StartFolder | where-object {$_.Psiscontainer -eq "True"} |select-object name

#Loop through folders
foreach ($Subfolder in $SubFolders)
{
Write-Host "Processing Folder:" $Subfolder

#For each folder recurse and delete files olders than specified number of days while the folder structure is left intact.
Get-ChildItem -Path $StartFolder$($Subfolder.name) -Include *.* -File -Recurse| Where LastWriteTime -lt  (Get-Date).AddDays(-$deletefilesolderthan) | foreach { $_.Delete()}

#$dirs will be an array of empty directories returned after filtering and loop until until $dirs is empty while excluding "Input" and "Output" folders.
do{
$dirs = gci $StartFolder$($Subfolder.name) -Exclude InputFolder,OutputFolder -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName
$dirs | Foreach-Object { Remove-Item $_ }
}while ($dirs.count -gt 0)

}
Write-Host "Completed" -ForegroundColor Green

The script is working fine in lower environments but as the data size increases in upper environment, it is taking more than 24 hours to complete and hence not clearing the data properly. I want to optimize it so that it will take less time to execute. Please help. 

Thanks.

Enumerate shares on remote servers

$
0
0

What is the difference between the old net view <computername> command and powershell command Get-SMBShare

Does it require more permissions for an account to run Get-SMBShare as opposed to running net view <computername> command? 

Are there any other functional difference between net view <computername> and Get-SMBShare commands?

Format a Variable with 01, 001

$
0
0

Hi all

I have a SharePoint site which orchestrator pulls the data from. The user types in a computer name and computer number. However due to the mess AD is in and people not using the naming standards they often use 1, 01 or 001 for the number. I have a script that checks the name against AD and if it exists if adds 1 and checks AD again until it finds a server name and number that doesn't exist. My issue is I cant get the variable to display what they entered in the number field with the leading zeros. I know "{0:D2}" -f [int]$Number will display the number based on value of D2 to show the leading zeros, but my problem is I don't know how many leading zeros they entered without looking at the SharePoint site. Is a trick to get the variable to show exactly what was entered without using a field that allows text?

Example

Server Name = "Server"
Number = "001"

$Number = "1"

I was going to use code to count the 0s and use If statement to send it down the correct route of {0:D2} or {0:D3} and create a range.

Any help would be appreciated

I know someone will just say "Get them to use the standards", but to keep the mess neater I need this to work.



Enable-WSManCredSSP does not change Client configuration

$
0
0

I have a Windows 7 VDI and am trying to set this with administrator PS (amusing I want to allow everything):

Enable-WSManCredSSP -Role Client -DelegateComputer * -Force

Once I run it, I get 

cfg         : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth
lang        : en-US
Basic       : Basic
Digest      : true
Kerberos    : true
Negotiate   : true
Certificate : true
CredSSP     : true

and then I run Get-WSManCredSSP to get this result:

The machine is not configured to allow delegating fresh credentials. 
This computer is not configured to receive credentials from a remote client computer.

I have tried a lot of things, including changing registry keys, editing the GPO policy in all ways possible - it always stays this way.

I have run this on several other PCs and servers with success. Any ideas why it does not work?



Getting RoboCopy PID with RoboCopy Arguments

$
0
0

Greetings,

I am trying to get the PID of RoboCopy when it is called in conjunction with arguments.  If I use the start-process cmdlet to call start-process with RoboCopy and the arguments, the RoboCopy operation will work, but I can't get the PID.

If I use the start command, I can get the PID of RoboCopy, however, I haven't been able to tag on the parameters to it trying variations such as "+arg", etc.  

I put the comments below on what happens with each command.  Any suggestions?  Thanks.

$run_robocopy = "robocopy"

$arg = "f:\ e:\ /mir /sec /r:10 /w:5 /log:c:\ProgramData\RoboCopy.log /tee"

start-process -wait $run_robocopy $arg                            # <-This runs RoboCopy, but the write-host output comes back as "write-host $GET_ROOBCOPY_PID" and shows the variable instead of the PID

$run_robocopy = [Diagnostics.Process]::Start("robocopy.exe")      # <-This will run RoboCopy and the write-host output comes back with the PID, however, I couldn't find a way to add the arguments without error.

$get_robocopy_pid  = $run_robocopy.Id

write-host $get_robocopy_pid

Auto approval of windows 7 asset to windows 10 by using windows 10 dashboard

$
0
0
  • Hi Guys,

    Good Evening !!

    Here is the thing on which I need ideas and help from you guys.

    Presently we are in that phase where we are migrating all the machines from Windows 7 to Windows 10.

    For this we are using windows 10 dashboard to approve the assets which are ready to migrate from 7 to 10 and presently we are doing it manually by going to dashboard site and then we have few options to enter the asset tag and then edit it and check the approved option and update so that the asset will be ready for the migration.

    And now comes my requirement.

    I want to automate this process using power-shell script every time when we get some request to approve one asset i want to write a script so that it will reduce the manual intervention and also reduce the time to approve the assets.

    I already wrote two line script like example by using invoke-webrequestcommand we can access the dashboard. from their on wards i am unable to move further like how to define new objects and all. 

  • I do not no how to define new objects and all by using windows 10 dashboard.

    Please do help me in this how to proceed or any ideas how to do this to approach our  requirement.

    Thanks in Advance :) 

Selecting a specific ProxyAddress

$
0
0

Hi Guys, 

I'm trying to search users based on e-mail from Domain A and take a specific proxy address from their list. I will then use that variable to put that as a targetAddress in Domain B. I cannot seem to find how to select a specific proxy address.

get-aduser -filter "Mail -like 'John.Smith@contoso.com'" -Properties ProxyAddresses | Select -ExpandProperty ProxyAddresses | Where $_ -like "*@MyDomain.com"

I keep receiving this error:

Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command aga
At line:1 char:120
+ ... -Properties ProxyAddresses | Select ProxyAddresses | Where $_ -like " ...
+                                                                ~~
    + CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand

I cannot use something like this because the proxies i want will be in different array indexes for everyone

$array = get-aduser -filter "Mail -like 'John.Smith@contoso.com'" -Properties ProxyAddresses | Select -ExpandProperty ProxyAddresses
$array[0]

Using the following command I can retrieve all the proxies in an array but cannot select a specific one.

get-aduser -filter "Mail -like 'John.Smith@contoso.com'" -Properties ProxyAddresses | Select -ExpandProperty ProxyAddresses





why isn't my shell object opening the SnippingTool app?

$
0
0

My computer was recently replaced and the script I run to prep my desktop isn't loading one of the apps (SnippingTool.exe). It's loading other apps, e.g., excel and notepad++ just fine. I know the path to the snipping tool is correct because I can go to that folder and open the app by double-clicking on it.  Below is the code

$myShell = new-object -comObject Shell.Application

$myShell.open("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe") #chrome
$myShell.open("C:\Program Files (x86)\Notepad++\notepad++.exe") #notepad++
$myShell.open("C:\Program Files (x86)\Microsoft Office\Office15\excel.exe") #excel
$myShell.open("C:\Windows\System32\SnippingTool.exe") #snipping tool

Remove-Variable myShell

The script runs fine on my old computer, including the snipping tool.  I can't figure out why it's not working on this box.

Christian Bahnsen

Viewing all 21975 articles
Browse latest View live


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