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

Remove Software by PowerShell

$
0
0

Hi Guys,

I create PowerShell Script to remove software but always show ReturnValue : 1603

I'm Domain admin , so my permission is Highest authority , I try use admin account and run as administrator but all show 1603.

Remove PC's OS is Win10-1903. WinRM is Open.

Is the Pulse this software problem?

How to solve it? Thanks!

My Script :

###################

$Date = (Get-Date).ToString("yyyMMdd-HHmm")

$computers = @(Get-Content 'C:\Test\testmchines.txt')
foreach ($computer in $computers){
    $Obj = New-Object PSCustomObject -Property @{ComputerName=$computer;TestExists=$false;Uninstalled=$false}

    $Test = Get-WMIObject -Class Win32_Product -Filter "Name Like '%Pulse Secure%'" -ComputerName $computer

    if ($Test){
        $Obj.TestExists = $true
        $result = $Test.Uninstall()
        if ($result -eq 0) {
            $Obj.Uninstalled = $true
        }
    }

    $Obj | Export-Csv D:\pcwork\pulse_$Date.csv -NoTypeInformation -Encoding UTF8
}


Hi I can't to find solution for solve this issue, I have Event 364 Source File: /Content/1B/DCD02B975BCC454188A2BB1F036E3E590C25641B.exe Destination File: D:\WSUS\WsusContent\1B\DCD02B975BCC454188A2BB1F036E3E590C25641B.exe But I don't know how to deline this KB Number..


Get lastlogon date and time

$
0
0

Hi , Can anyone assist with how I can include the lastlogon date and time for each user with this script. The date format is dd/mm/yyyyy . 

Any assistance with this would be most appreciated.

Get-ADUser -Filter * -Properties ou | Select Name, SamAccountName, @{n='OU';e={($_.distinguishedName -Split ",")[1].Replace("OU=", "").Replace("CN=", "")}} | Export-Csv "C:\users1.csv" -Encoding "Unicode"

Populate Certificate's Intended Purpose - EnhancedKeyUsageList

$
0
0

Hi,

When I import a certificate, the intended purpose is <All>.  I'm trying to populate the intended purpose with just a select few purposes.

When I run the following commands:

$Cert = Get-ChildItem | where {$_.Subject -match "Certain Certificate"}

$Cert.EnhancedKeyUsageList = "Server Authentication (1.3.6.1.5.5.7.3.1), Client Authentication (1.3.6.1.5.5.7.3.2)"

I get the following error:

'EnhancedKeyUsageList' is a ReadOnly property.

Anyway of populating that field via Powershell?  Thanks.

Get-ADComputer foreach loop error

$
0
0

COuld any one help on below script I get error : 

Script : 

 

$comps = Get-Content -Path C:\Users\adey\Desktop\computers.txt

foreach ($comp in $comps)

{  

$compdata = get-adcomputer $comp -properties PasswordLastSet |ft Name,PasswordLastSet

   write-host "$comp" 
   Write-Host "$compdata"

   }

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

Out Put : 

PS H:\> S:\Ares\GetLastPwdChange.ps1

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

I'm new to PS. Could any one please suggest correction on this script

New-InformationBarrierPolicy does not work

$
0
0

I am setting up barrier policy. I was able to create segments and run the 'Get-RetentionCompliancePolicy' command without any error.

However New-InformationBarrierPolicy command returns the error: '

 The term 'New-InformationBarrierPolicy' 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.

'

I am working at the same PowerShell session when I created segments, so the command should be included/imported.

I have enabled as well 'Scope directory search using an Exchange address book policy' on Teams.

Full command that I ran is

New-InformationBarrierPolicy -Name "Internal-Company A" -AssignedSegment "Company A Restricted" -SegmentsAllowed "Internal","Company A Restricted" -State Inactive                     

Could you help me work out with running theNew-InformationBarrierPolicy command 

set variable for folders

$
0
0

Hi I have one question I need set variable for folders

I have many folders with name "secure" I want to grant full access permissions to "Domain Users" for all "secure" folders

but I have different names for example:

f:\home\User1\secure

f:\home\Usere2\secure

f:\home\User3\secure

How can I set variable in script for user1,user2,user3 if I write f:\home\*\secure it is not work, for one user it work, script bellow:

Invoke-Command -ScriptBlock {

cd f:\home

$Acl = Get-Acl "f:\home\User1\secure"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("Domain Users", "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "f:\home\User1\secure" $Acl

} -ComputerName FS1 -Credential test.local\administrator


System administrator


registering new scheduled task - does not "run whether user is logged on or not"

$
0
0

Hi all,

Summary:

My code can successfully register new events running as SYSTEM. However, when I supply an account and password (which has log on as batch job permissions) I cannot get it to register the task as "run whether user is logged on or not".

I've read about 17 articles and tried sample code from 5 or 6 of the top search sources, but can't seem to resolve this. Almost everything I found on the topic says that if I supply both username and password of a domain account with the correct privileges, the task will be created with the desired properties. However, some references claim that if I register the task using a Principal and -LogonType Password that it will work as desired, but that's not true. Some claim that -LogonType should be S4U for the desired behaviour. That also is not true. For one thing, I tried it (And I tried all -LogonType options) out of desperation.  Secondly, it doesn't make sense because to get the desired behaviour a password must be supplied, but by using a Principal, there is no mechanism for supplying a password, at least not in New-ScheduledTaskPrincipal, New-ScheduledTask, or Register-ScheduledTask.

I have also tried -RunLevel Highest and -RunLevel Limited.

The goals:

  • the task must run whether any user is logged on or not
  • the task must have access to network resources (UNC shares)

The code:

Register-ScheduledTask -TaskName "$Taskname" -Description "$Description" `            
    -Action $Action -Trigger $Trigger -Settings $Settings -RunLevel Highest `            
    -User "$DomainUser" -Password "$Password" `            
    -ErrorAction Stop

As I said, this (final) code is mostly working, but not as desired. If I run this code, the task is created, but is set to "Run only when user is logged on".  I can then go into the GUI, manually edit the task and set it to "Run whether user is logged on or not", enter the same password used in the code above, and then all works as expected.  However, it completely defeats the purpose of creating the scheduled task in code.

The plea:

I have spent way too much time on this, but any suggestions would be greatly appreciated!

Brian Perkins
Luanda International School of Angola

Powershell Obtaining Value of Contact Name in WebPart

$
0
0

All,

I have this Powershell where I am trying to loop through all pages on a on-premise SharePoint 2013 environment and output the user name value from a contact details web part - the script no matter what I do displays the Site Owner value as ' ' since this is a People Picker based value - is their something else I need to do - to obtain the value I am looking for. The field name in the webpart properties for the People Picker - is Contact.

Add-PsSnapin Microsoft.SharePoint.PowerShell
###############################################################################
# This script will loop through a web app and output site owner contact and URL
###############################################################################
#Get All Webs (sites)

$webs = Get-SPWebApplication "https://intranet.mydomain.com" | Get-SPSite -Limit All | Get-SPWeb -Limit All

 #Iterate through webs

 foreach ($web in $webs)

 {

  #Get All Pages from site's Root into $AllPages Array

  $AllPages = @($web.Files | Where-Object {$_.Name -match ".aspx"})

 

  #Search All Folders for Pages

  foreach ($folder in $web.Folders)

      {

          #Add the pages to $AllPages Array

          $AllPages += @($folder.Files | Where-Object {$_.Name -match ".aspx"})

      }


   #Iterate through all pages

   foreach($Page in $AllPages)

     {

       #Web Part Manager to get all web parts from the page

        $webPartManager = $web.GetLimitedWebPartManager($Page.ServerRelativeUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

       #Iterate through each web part

       foreach($webPart in $WebPartManager.WebParts)

          {

            #$siteOwner=$webPart.Contact
            $FieldName="Contact"
            $siteOwner = New-Object Microsoft.Sharepoint.SPFieldUserValue($web,$webPart[$FieldName])
         $accountName = $siteOwner.User.Email
           
            #Get the Content Editor web part with specific Title

            if($webPart.title -like "Site Owner")

             { 

                  write-host "SiteOwner '$($accountName)' on $($web.URL)$($Page.ServerRelativeUrl)"

             }

         }

      }

  }


How do I get 'Write-Host' to output to a csv file?

$
0
0

I have this function that I am calling to give me a list of all lists and libraries within a SharePoint site and it's subsites. Right now, the code outputs the data to the console using the Write-Host and it works just fine. How do I get this to output the data to a csv file? 

Function Get-SPOList($Web)
    {
        #Get All Lists from the web
        $Lists = $Web.Lists
        $Context.Load($Lists)
        $Context.ExecuteQuery()
        #Get all lists from the web  
        ForEach($List in $Lists)
        {
            #Get the List Name
            Write-host $List.Title             

        }
        
    }
Thanks for the help. 

Writing ComputerName value to Write-Host

$
0
0

Hi

Currently stuggling to get the actual computer to be written to Write-Host

    if (Test-Connection $_.Name -Count 1 -Quiet) {
    Write-Host {"$_.Name Online"}

I'm getting the syntax wrong somewhere but cannot figure out where?

Any help really appreciated guys

not so complicated script too complicated for me.

$
0
0

Hi!
I would like to make a script with few steps:
1. Find files (not directories) in particular directory recusively older than NumberDays
2. Move/copy this file to other path preserving full path string
3. Create file which name is the same as moved with additional .txt extension and wchich contain the string "this file was moved"


behaving:
x:\source-directory\sub-directory1\sub-directory2\sub-directory3\very.old.file.pdf
Should be copied/moved to:
x:\destination-directory\sub-directory1\sub-directory2\sub-directory3\very.old.file.pdf
new file should be created containing "this file was moved"
x:\source-directory\sub-directory1\sub-directory2\sub-directory3\very.old.file.pdf.txt

.1:
$NumberDays = 1000
$SourcePath = 'x:\source-directory'
$DestinationPath = 'x:\destination-directory'
$OldDate = (Get-Date).AddDays(-$NumberDays)

Function Get-OldFiles
{
 Get-ChildItem -Path $SourcePath -recurse | Where-Object {$_.LastWriteTime -le $OldDate}
 }


.2:
Copy-Item -Destination $DestinationPath -Recurse

Combining 1 plus 2:

Get-OldFiles | Copy-Item -Destination $DestinationPath -Recurse
Result is messing with the directories :
x:\destination-directory\sub-directory3\very.old.file.pdf instead of x:\destination-directory\sub-directory1\sub-directory2\sub-directory3\very.old.file.pdf
No idea how to fix :(.

.3:
No idea at all :(
New-Item -Path ??? -Name "?????.txt" -ItemType "file" -Value "this file was moved"

How do I get data returned on console, to a csv file?

$
0
0

I want to use PowerShell to return all the lists and libraries in a Site Collection and subsites. Secondly, I want to return the data in a csv file. I have found this script that loops through the site and subsites, but I have not been able to tweak it to return the data in a csv file. Right now, it just prints out to console 'Write-host'. 

Is there a way to get this to output the data to a csv file? 

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/sales"
$UserName="salaudeen@crescent.com"
$Password ="Password goes here"
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
Try {
    #Function to Get all lists from the web
    Function Get-SPOList($Web)
    {
        #Get All Lists from the web
        $Lists = $Web.Lists
        $Context.Load($Lists)
        $Context.ExecuteQuery()
        #Get all lists from the web  
        ForEach($List in $Lists)
        {
            #Get the List Name
            Write-host $List.Title
        }
    }
    #Function to get all webs from given URL
    Function Get-SPOWeb($WebURL)
    {
        #Set up the context
        $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebURL)
        $Context.Credentials = $Credentials
        $Web = $context.Web
        $Context.Load($web)
        #Get all immediate subsites of the site
        $Context.Load($web.Webs) 
        $Context.executeQuery()
        #Call the function to Get Lists of the web
        Write-host "Processing Web :"$Web.URL
        Get-SPOList $Web
        #Iterate through each subsite in the current web
        foreach ($Subweb in $web.Webs)
        {
            #Call the function recursively to process all subsites underneaththe current web
            Get-SPOWeb($SubWeb.URL)
        }
    }
    #Call the function to get all sites
    Get-SPOWeb $SiteUrl
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Thanks.

Problems applying ACL

$
0
0

Let me first say thank you in advance for your help.

We have stood up a new forest, we will say ABC.

We also have our original forest , we will sat MSC.

There is an intrinsic trust between the domains, and all Users and Groups have been migrated from MSC to ABC.

We have an EMC File Server which has home folders and department shares.  I created a PowerShell Script to read each folder and perform a Get-ACL which created a CSV file with the Users/Groups names, Filesystem Rights, Inheritance, Propagation flags, Access Control Type.

What I am trying to do, add the same users/Groups from new Domain ABC with the same ACL Security as the corresponding Security from Domain MSC.  This will then Dual ACL the File Server with both domains.

The CSV file I created has most of the information I need.

This is the error I am getting when running the script;

Set-acl : AclObject
At \\rtihomenas\Public\MIS\Network-Telecomm\citrix\Scripts\scripts\IsilonACLApply.ps1:51 char:29
+ ...                           Set-acl $FilePath $ACLRule
+                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (System.Security...ystemAccessRule:FileSystemAccessRule) [Set-Acl], ArgumentException
    + FullyQualifiedErrorId : SetAcl_AclObject,Microsoft.PowerShell.Commands.SetAclCommand

Below is my script;

Connect-QADService -service DomCtrl.ABC.US –proxy -credential ABC\adm.AdminUser1

        $InFile = "C:\Shares\Folders.csv"
                    $file = import-csv $InFile
                    foreach($Sec in $file) {
                        $FilePath = $Sec.Folder_Path
 
                        $IDRef = $Sec.IdentityReference
 
                        $ACCType = $Sec.AccessControlType
 
                        $FSType = $Sec.FileSystemRights

                        $IsInhert = $IsInherit

                        $InhertFlg = $Sec.InheritanceFlags

                        $PFlags = $Sec.PropagationFlags
 
                        $ObjInheritFlg = $Sec.ObjectInhert
       #This line will get the account/group from Domain ABC.
                        $objGroup = Get-QADGroup -Identity $IDRef | Select-Object -ExpandProperty SamAccountName
                        $objADGroup = $objGroup
                            Write-Host "Name is: " $objADGroup
                            $Matches = $objADGroup -match $IDRef.trimstart("ABC\")
                            If ($Matches -eq $True) {

                            $objGrp = New-Object System.Security.Principal.NTAccount "$objGroup"  
                                Write-Host "Name is " $objGrp

                            $colRights = [System.Security.AccessControl.FileSystemRights]::$FSType
                                Write-Host "FileSystem Type: " $colRights 
                            
                            $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit
                                Write-Host "Inheritence: " $InheritanceFlag 

                            $PropagationFlag = [system.security.accesscontrol.PropagationFlags]::None
                                Write-Host "Propagation Flag: " $PropagationFlag

                            $objType = [System.Security.AccessControl.AccessControlType]::$ACCType
                                Write-Host "Account Type: "$objType
                            
                            #$ACLRule = New-Object System.Security.AccessControl.FileSystemAccessRule($objGroup,$colRights,$InheritanceFlag,"None",$objType)

         #Add this line to explicitly add the Rights
        $ACLRule = New-Object System.Security.AccessControl.FileSystemAccessRule("ABC-File Administrators","FullControl","ContainerInherit,ObjectInherit","None","Allow")
                            
                            #($objGrp,$colRights,$InheritanceFlag,"None",$objType)

                            $Fldracl = get-acl $FilePath
                            $Fldracl.AddAccessRule($ACLrule)
                            Set-acl -Path $FilePath -aclObject $ACLRule
                            }
                            }

Any help that you can provide will be greatly appreciated.

JSON output structure

$
0
0

I'm hoping someone can help me, I'm trying to get the output of a SQL query into a specific JSON structure.

The script I currently have is as follows:

$sqlCmd = @"
SELECT * 
FROM SQL_VIEW"@

$results = Invoke-SqlCmd -Query $sqlCmd -ServerInstance "SQL_SERVER_INSTANCE"

$data = foreach ($grp in $results | Group-Object -Property idnumber){
	[ordered]@{
	data = @($grp.Group[0] | Select-Object email,firstname,surname,idnumber,title,gender,nino)
	courses = @($grp.Group | Select-Object @{l='projectid';e={courses.projectid}},@{l='courseid';e={courses.courseid}},@{l='startdate';e={courses.startdate}})
	}
}

$body = ConvertTo-Json -InputObject $data -Depth 3 | Out-File "c:\test\import.json"

I've currently got two issues, the first is that the courses array doesn't appear to show me any values and just returns null values even though there is data there. The SQL columns are labelled with the 'courses.' prefix, but I need to exclude this prefix from the JSON.

The second issue is that the JSON depth really needs to only be two levels deep and not three, the following is an example of the structure I need this in:

{"data":[
      {"email": "someone@somewhere.com","firstname": "John","surname": "Smith","idnumber": "123456","title": "Mr","gender": "M","nino": "AB123456C","courses":[
            {"projectid":"1234","courseid":"4567","startdate":"01/01/1900"
            },
            {"projectid":"1111","courseid":"4444","startdate":"01/10/1900"
            }
         ]
      },
      {"email": "someone@somewhere.com","firstname": "Jack","surname": "Smith","idnumber": "99999","title": "Mr","gender": "M","nino": "AB654321C","courses":[
            {"projectid":"1234","courseid":"4567","startdate":"01/01/1900"
            },
            {"projectid":"1111","courseid":"4444","startdate":"01/10/1900"
            }
         ]
      },
   ]
}

Do I need to do much more to my script in order to do this?

create wildcard search based on char plus any numerical number

$
0
0

I want to use PS to create a wildcard search based on location name. (example location name: CA01,CA02).

If I use the logic: if ($loc -like "CA*")  then do-something. It will find any location name start contain CA, is there a way I can use a wildcard to contain char (CA) plus any numerical number, so the script will only find location name contain CA01, CA02......

Thank you in advance..


How to remove Column and row on excel file

$
0
0

Hi guys.
I have used the script below to remove column (first 4 Columns) and row (first 13 rows) and it has worked.
However, now I am testing the same script in a new excel file with a button (image) and it is no longer working.
Is there a way to force the removal, even if there is a button, macro or other things inside a file?
Can you help me please?

This is the script 

$ExcelPackage = Open-ExcelPackage -Path C:\Local\test.xlsx
$ExcelPackage.Workbook.Worksheets[1].DeleteRow(1,13)
$ExcelPackage.Workbook.Worksheets[1].DeleteColumn(1,4)

How to keep my game running in background?

$
0
0

Hi there.

I would like my game, Frozen Throne.Exe, running in background while I ran another things like typing , watching media ,etc

I tried run the game in Windowed, alt+tab to switch to another program, but it still paused everytime I open another things.

How do I keep it running in background? thanks

Get-AzureADUser O365 license info

$
0
0

Hi,

When I run the following I don't see any license info:

Get-AzureADUser -all $true -filter "UserType eq 'Guest'" | select AssignedLicenses,AssignedPlans,DisplayName,Mail,RefreshTokensValidFromDateTime,UserState,UserStateChangedOn

When I export it to CSV I see info populated more than to the console, but for AssignedLicenses and AssignedPlans it's returning:

System.Collections.Generic.List`1[Microsoft.Open.AzureAD.Model.AssignedLicense]

System.Collections.Generic.List`1[Microsoft.Open.AzureAD.Model.AssignedPlan]

Can anyone suggest how to return the correct values for these, I essentially just want to figure out which licenses have been assigned to Guest users.

Thanks

Paralel Excution

$
0
0
When I call a function in PS script, it has to wait until the function execution is done before continuing the rest. In Powershell, is there a way to call the function and then continuing without waiting. It is something like parallell processing? thanks.

Simple double if script not working

$
0
0

Hi guys, please someone help with the simple few lines below

Getting the error shown

else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program.

_______________________________________________________

$Computers = Get-Content C:\scripts\ComputerName.txt
$Computers | ForEach-Object {
    if (Test-Connection $_ -Count 1 -Quiet)
    {Write-Host "$_ is online"}


    if (Test-WSMan -ComputerName $_.Name -ErrorAction SilentlyContinue) {
        Write-Host "$($_.Name) - WinRM Enabled" }
        else { Write-host "$($_.Name) - WinRM Disabled "}


    else {
        
        Write-Host "$_ is offline"

        }
}

Viewing all 21975 articles
Browse latest View live


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