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

How to resolve Windows PowerShell ISE has stopped working in server 2008 r2 ?

$
0
0

Hi all,

        I have been installed latest windows power shell updates on my system. after installation when opening the windows command ISE not supporting .net frame work 4.0 issue showed. uninstalled the latest power shell updates version 5.0 on my system. after opening the windows power shell command ISE  showing Windows Power Shell ISE has stopped working issue. i am unable to open the windowspower shell command window. can please provide proper solution to resolve this issue.

Thanks in advance

Regards

by

Narasimman



Can we run PowerShell 7 in PS ISE?

$
0
0

I wanted to run ForEach-Object -Parallel code and found that it needs PS7. I installed it and can see separate PS7 installed which just has normal console, not good UI interface like PS ISE. 

So is there any way to run PS7 code in ISE directly? Or any other tool now like VS Code? What do you PS expert guys use mostly? 


If the response helped, do "Mark as answer" and upvote it
- Vaibhav

PowerShell to get information VPN

$
0
0

Hello Guys, 

I need some help, I need to get some information using the PowerShell

a) User

b) date

c) time do start / finish

d) how long use the VPN

Can someone help me please ?

Thanks

Login script delete MS Teams files and set config

$
0
0
Hi I’m trying to get a login script to work that deletes the files in a users profile folder for MS Teams and then sets the desktop config file to disable the GPU acceleration. I’ve tried the script below and it works if I run it logged into the server manually as an admin. If I set it in a Glo it doesn’t run and if I set it in a users account properties in AD then it doesn’t run. I want to use a gpo. 
remove-item $env:userprofile\AppData\Roaming\Microsoft\Teams\* -exclude desktop-config.json -Recurse -Force -Confirm:$False | 
(Get-Content $ENV:APPDATA\Microsoft\Teams\desktop-config.json).replace(‘”disableGpu”:false’, ‘”disableGpu”:true’) | Set-Content $ENV:APPDATA\Microsoft\Teams\desktop-config.json


Beginner in PowerShell

$
0
0

I am learning power Shell and wrote below script but i got an error i couldn't fix it? could you please help!

-Error: Unexpected token 'Until' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

-Script:

$intfolders = 10
$intpad = 0
$i = 1
New-Variable -Name StrPrefix -Value "testfolder" -Option Constant
{
if ($i -lt 10)
{New-Item -Path c: -Name $strprefix$intpad$i -type directory}
else
{New-Item -Path C: -Name $strprefix$i -type directory}
$i++
} Until ($i -eq $intfolders +1)

At line:11 char:3
+ } Until ($i -eq $intfolders +1)
+   ~~~~~
Unexpected token 'Until' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

 

Select-Object returning selected PSCustomobject instead of selected type

$
0
0

Hello,

I've asked this question at powershell.org as well

https://powershell.org/forums/topic/retain-type-when-using-select-object/#post-231241

When I am looking at objects and pipe to Select * - they seem to always have type of 'selected dot whatever the original type' was. When I do the same with modules from the PSGallery, they come back as PSCustomObject and are no longer able to be piped into install-module. Like I said there, I understand I can work around it but it seems like either the select-object cmdlet or powershellget provider is not doing something correctly. I found some articles online that discuss similar questions, but they are actually selecting custom properties making a custom object. I'm just wanting all members of the object. I appreciate any input. 

This works fine

Find-Module -Name *somemodule* | install-module

Find-Module -Name *somemodule* | install-module

This fails

Find-Module -Name *somemodule* | select * | install-module Install-Module : Invalid value is specified for InputObject parameter.

Find-module -Name a* | get-member

    TypeName: Microsoft.PowerShell.Commands.PSRepositoryItemInfo

Find-Module -name a* |select -first 1 -Property * | get-member

    TypeName: Selected.System.Management.Automation.PSCustomObject

Which is to blame?

Sorting and gathering contents with a PS script *** Complete NOOB ***

$
0
0

Hello,

Goal of this post:
1. Sort Name column with csv filter -contains "-POS-"
2. Only pull back the top Bitlocker key from AzureAD and place that one key into the bitlockerKeys column.

This is a script from - https://gitlab.com/Lieben/assortedFunctions/blob/master/get-bitlockerEscrowStatusForAzureADDevices.ps1

This is not my script, but I need it to work like this for a project I am doing. Did I mention that I am a complete PS noob here? Take it easy on me please lol.

 function get-bitlockerEscrowStatusForAzureADDevices{
    #Requires -Modules ImportExcel<#
      .SYNOPSIS
      Retrieves bitlocker key upload status for all azure ad devices
      .DESCRIPTION
      Use this report to determine which of your devices have backed up their bitlocker key to AzureAD (and find those that haven't and are at risk of data loss!).
      Report will be stored in current folder.
      .EXAMPLE
      get-bitlockerEscrowStatusForAzureADDevices
      .PARAMETER Credential
      Optional, pass a credential object to automatically sign in to Azure AD. Global Admin permissions required
      .PARAMETER showBitlockerKeysInReport
      Switch, is supplied, will show the actual recovery keys in the report. Be careful where you distribute the report to if you use this
      .PARAMETER showAllOSTypesInReport
      By default, only the Windows OS is reported on, if for some reason you like the additional information this report gives you about devices in general, you can add this switch to show all OS types
      .NOTES
      filename: get-bitlockerEscrowStatusForAzureADDevices.ps1
      author: Jos Lieben
      blog: www.lieben.nu
      created: 9/4/2019
    #>
    [cmdletbinding()]
    Param(
        $Credential,
        [Switch]$showBitlockerKeysInReport,
        [Switch]$showAllOSTypesInReport
    )

    Import-Module AzureRM.Profile
    if (Get-Module -Name "AzureADPreview" -ListAvailable) {
        Import-Module AzureADPreview
    } elseif (Get-Module -Name "AzureAD" -ListAvailable) {
        Import-Module AzureAD
    }
    if ($Credential) {
        Try {
            Connect-AzureAD -Credential $Credential -ErrorAction Stop | Out-Null
        } Catch {
            Write-Warning "Couldn't connect to Azure AD non-interactively, trying interactively."
            Connect-AzureAD -TenantId $(($Credential.UserName.Split("@"))[1]) -ErrorAction Stop | Out-Null
        }
        Try {
            Login-AzureRmAccount -Credential $Credential -ErrorAction Stop | Out-Null
        } Catch {
            Write-Warning "Couldn't connect to Azure RM non-interactively, trying interactively."
            Login-AzureRmAccount -TenantId $(($Credential.UserName.Split("@"))[1]) -ErrorAction Stop | Out-Null
        }
    } else {
        Login-AzureRmAccount -ErrorAction Stop | Out-Null
    }
    $context = Get-AzureRmContext
    $tenantId = $context.Tenant.Id
    $refreshToken = @($context.TokenCache.ReadItems() | where {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
    $body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
    $apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
    $restHeader = @{
        'Authorization' = 'Bearer ' + $apiToken.access_token
        'X-Requested-With'= 'XMLHttpRequest'
        'x-ms-client-request-id'= [guid]::NewGuid()
        'x-ms-correlation-id' = [guid]::NewGuid()
    }
    Write-Verbose "Connected, retrieving devices..."
    $restResult = Invoke-RestMethod -Method GET -UseBasicParsing -Uri "https://main.iam.ad.ext.azure.com/api/Devices?nextLink=&queryParams=%7B%22searchText%22%3A%22%22%7D&top=15" -Headers $restHeader
    $allDevices = @()
    $allDevices += $restResult.value
    while($restResult.nextLink){
        $restResult = Invoke-RestMethod -Method GET -UseBasicParsing -Uri "https://main.iam.ad.ext.azure.com/api/Devices?nextLink=$([System.Web.HttpUtility]::UrlEncode($restResult.nextLink))&queryParams=%7B%22searchText%22%3A%22%22%7D&top=15" -Headers $restHeader
        $allDevices += $restResult.value
    }

    Write-Verbose "Retrieved $($allDevices.Count) devices from AzureAD, processing information..."

    $csvEntries = @()
    foreach($device in $allDevices){
        if(!$showAllOSTypesInReport -and $device.deviceOSType -notlike "Windows*"){
            Continue
        }
        $keysKnownToAzure = $False
        $osDriveEncrypted = $False
        $lastKeyUploadDate = $Null
        if($device.deviceOSType -eq "Windows" -and $device.bitLockerKey.Count -gt 0){
            $keysKnownToAzure = $True
            $keys = $device.bitLockerKey | Sort-Object -Property creationTime -Descending
            if($keys.driveType -contains "Operating system drive"){
                $osDriveEncrypted = $True
            }
            $lastKeyUploadDate = $keys[0].creationTime
            if($showBitlockerKeysInReport){
                $bitlockerKeys = ""
                foreach($key in $device.bitlockerKey){
                    $bitlockerKeys += "$($key.creationTime)|$($key.driveType)|$($key.recoveryKey)|"
                }
            }else{
                $bitlockerKeys = "HIDDEN FROM REPORT: READ INSTRUCTIONS TO REVEAL KEYS"
            }
        }else{
            $bitlockerKeys = "NOT UPLOADED YET OR N/A"
        }

        $csvEntries += [PSCustomObject]@{"Name"=$device.displayName;"bitlockerKeys"=$bitlockerKeys}
    }
        $csvEntries | Export-Excel -workSheetName "BitlockerKeyReport" -path "C:\BitLockerKeyReport.xlsx" -ClearSheet -TableName "BitlockerKeyReport" -AutoSize -Verbose
}

get-bitlockerEscrowStatusForAzureADDevices -showBitlockerKeysInReport

Thanks,

Kevin

Install SQLServer Module

$
0
0

Hi,

I need to use a script that uses "Invoke-Sqlcmd", but I'm in this situation:

 - The server does not have sqlServer modules
 - The server is a Tools/Scripts server.
 - The server does not have SQL Server
 - The server does not have  SQL Server Management Studio
 - The server does not have an internet connection

What is the best way to install requires modules (so I can use Invoke-Sqlcmd)?

Tks,

JD



Log warning messages

$
0
0

Hi 

I have a script that, when runs in interactive console, displays some warning messages to the console
I would like to have those messages captured (even when run unattended) to be able to add them to my application log.

Note: I can't use transcript, I receive the error below and 3 & 4 redirection does not have the desired effect 
Start-Transcript : This host does not support transcription.

What is the best way to add those warning messages (and also non-terminating errors) to my application log file?

Thanks,

JD

Userprofile path test across multiple servers

$
0
0

Good Afternoon

I wish to check across our 10 Windows Servers for all users that appear to have a Microsoft Teams profile folder.

I have used the below to test on my current logged on server and this responds with a simple True or False, it does not show me which user is true / False

$users = Get-ChildItem C:\Users
Foreach ($user in $users){
  (test-path "$($user.fullname)\AppData\Local\Microsoft\Teams\current\Teams.exe")
    }

Is it possible to do a check across each server using a foreach? i could simply list the users in a txt document to make this easier

I would like t see the users name and a true / false response

I hope this makes sense

B

Try Catch - Unexpected behaviour

$
0
0

Hi

I have a script with an unexpectd behaviour when inside a try-catch block

The $ErrorActionPreference is Continue
The script does Get-ADUser xyz  -ErrorAction SilentlyContinue
When no try-catch block is used, the script continues to next statements
When the Get-ADUser xyz  -ErrorAction SilentlyContinue is used inside a try-catch block, the script jumps to the catch block (Cannot find an object with identity: 'xyz' under: xxx).

Shouldn´t the -ErrorAction specified allow me to continue and have the try-catch take effect only to other errors on other commands inside the block?

Thanks,

JD

removing winrm https listener on remote machine

$
0
0
any idea how to remove the winrm HTTP listener on tcp 5986? how can i do that remotely to another machine?

How to get output from ForEach-Object to show up as a numeric sum?

$
0
0

The code below checks all sub OUs with the name = Test to find active accounts.  The problem is that each OU will output a different number per line and I was hoping to find a way to just output the numeric sum of all the OUs.  Any ideas?

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

# Check for active accounts in Test Sub-OUs

"Total active accounts in Test Sub-ous: "

$Test = Get-ADOrganizationalUnit -Filter "Name -eq 'Test'"

$Test | ForEach-Object{

    (Get-ADUser -Filter * -SearchBase $_.DistinguishedName | Where {$_.enabled -eq "True"}).count

    }

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

Output looks like this:

7

8

0

0

10

Powershell scripting

$
0
0

Hello,

I'm working on project. I need to extract all the users connected to the domain computers since the last year.

in other word, I need to know the users connected to each computer on the domain since the last year.

So, if you know a tool or you have a script that I can adapt to my environnement will be appreciate it

Thank you

Optimize Powershell Script which sends a notification based on Network Location

$
0
0

This is what the script is supposed to do

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

 

• Check whether client VPN is active

o If yes: check whether the domain / a DC can be reached (e.g. "ping rX.company.net", should come from a COMPANY VPN)

 Show notification according to whatever criteria

o If no: check whether the domain / a DC can be reached

 Yes: Computer is in the COMPANY corporate network  Send / display notification

 No: Computer is neither connected via VPN nor COMPANY corporate network  No notification

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

 

#$ActiveDomainVPN = Get-NetConnectionProfile  -Name "company.net" -InterfaceAlias "COMPANY VPN wCA" | Where {$_.NetworkCategory -match 'DomainAuthenticated'}

#$ActiveDomain = Get-NetConnectionProfile -Name "company.net" -InterfaceAlias "ethernet" | Where {$_.NetworkCategory -match 'DomainAuthenticated'}

#$IP = Get-NetIPAddress | where {$_.IPAddress -match '10.*.*.*'}

 

#match criteria based on condition and display message

$ActiveDomainVPN = Get-NetConnectionProfile  -Name "company.net" -InterfaceAlias "COMPANY VPN wCA" -NetworkCategory "DomainAuthenticated"

$ActiveDomain = Get-NetConnectionProfile -Name "company.net" -InterfaceAlias "ethernet" -NetworkCategory "DomainAuthenticated"

$IP = Get-NetIPAddress -IPAddress "10.*.*.*"

 

#display message if Active VPN and Domain network can be reached

if ($ActiveDomainVPN -eq $IP)

{

[System.Windows.Forms.MessageBox]::Show("Main text here Main Text here." ,'Closing time!',0,48)

Break

}

#display message if Domain network can be reached

elseif ($ActiveDomain -eq $IP)

{

[System.Windows.Forms.MessageBox]::Show("Main text here Main Text here." ,'Closing time!',0,48)

Break

}

#Dont display message if above criteria is not met

else

{

Exit

}

Suggestions on code improvement will be welcomed 



Optimize Powershell Script which sends a notification based on Network Location (should match Corporate Network)

$
0
0

This is what the script is supposed to do

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

 

• Check whether client VPN is active

o If yes: check whether the domain / a DC can be reached (e.g. "ping rX.company.net", should come from a COMPANY VPN)

 Show notification according to whatever criteria

o If no: check whether the domain / a DC can be reached

 Yes: Computer is in the COMPANY corporate network  Send / display notification

 No: Computer is neither connected via VPN nor COMPANY corporate network  No notification

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

 

#$ActiveDomainVPN = Get-NetConnectionProfile  -Name "company.net" -InterfaceAlias "COMPANY VPN wCA" | Where {$_.NetworkCategory -match 'DomainAuthenticated'}

#$ActiveDomain = Get-NetConnectionProfile -Name "company.net" -InterfaceAlias "ethernet" | Where {$_.NetworkCategory -match 'DomainAuthenticated'}

#$IP = Get-NetIPAddress | where {$_.IPAddress -match '10.*.*.*'}

 

#match criteria based on condition and display message

$ActiveDomainVPN = Get-NetConnectionProfile  -Name "company.net" -InterfaceAlias "COMPANY VPN wCA" -NetworkCategory "DomainAuthenticated"

$ActiveDomain = Get-NetConnectionProfile -Name "company.net" -InterfaceAlias "ethernet" -NetworkCategory "DomainAuthenticated"

$IP = Get-NetIPAddress -IPAddress "10.*.*.*"

 

#display message if Active VPN and Domain network can be reached

if ($ActiveDomainVPN -eq $IP)

{

[System.Windows.Forms.MessageBox]::Show("Main text here Main Text here." ,'Closing time!',0,48)

Break

}

#display message if Domain network can be reached

elseif ($ActiveDomain -eq $IP)

{

[System.Windows.Forms.MessageBox]::Show("Main text here Main Text here." ,'Closing time!',0,48)

Break

}

#Dont display message if above criteria is not met

else

{

Exit

}

Suggestions on code improvement will be welcomed 



Invoke-Sqlcmd unattended execution

$
0
0

Hi

I have a script that works just fine when executed in an interative session

When it runs via a scheduler task, the script seems to hang  rigth after theInvoke-SqlCmdand no more logs are done

Note: the account configured in the Scheduler Task is the same one  used in the interactive session

Is there any restriction on using Invoke-SqlCmd unattended?

thanks,

JD

What operator can I use to return two values from a multi valued string?

$
0
0

Hi, I am trying to search for a user based on the two values returned from $_.Licenses.AccountSKUID

But the -eq operator will only return the results for the first match and not the other.  

get-MSOLUser -All | where {$_.isLicensed -eq "TRUE" -and $_.Licenses.AccountSKUID -eq "sku_id1" -and "sku_id4"}

How can I get it to work? 

Thanks 


move-item : Access to the path '...' is denied

$
0
0

I am trying to clean up the homefolder drive where I work. Currently there are a ton of homefolders that do not have matching AD accounts. I have identified all of the folder paths, and ran scripts to pull the paths into txt files. There are 2 sites each for 2 different networks I am doing this on.  2 sites on one network and 1 site on the other network worked fine, but I am having issues on the last site\network. 

For each site and network, all homefolders reside on a share on a NetApp, and the destination in the script is a separate folder within the same share on the same NetApp as its source location.

On the site\network I am having issues with, the structure looks like this

\\location\users1

\\location\users2

\\location\users3

\\location\users4

I have created an archive folder \\location\Archive\Delete_On_Date.

My script looks like this

$file1 = Get-Content \\sourcefiles\homefolder_archive_date.txt
move-item -path $file1 -destination \\location\Archive\Delete_On_Date

I get the following error

move-item : Access to the path '<Provides a path to one of the paths listed in the source file>' is denied

I have checked, double checked, and triple checked permissions, looking for explicit deny, looking at both the share and NTFS permission sets.  I have tried running as user and as admin, no matter what, I get this error.  I have tested manually moving a folder that gets the access denied error and it is successful.

NOTE:  The really odd part of this is that after tons of testing and troubleshooting, I found that the script works perfectly fine on the users1 and users4 folders, but errors on the users2 and users3 folders.

Any ideas?

Can I use variable to remap network drives from an IP address to a server name?

$
0
0

I manage servers at some of our remote sites, and some of my users have their drives mapped as an IP address, but we are moving to have all drives as a "\\ServerName\File" format. Can I assign a variable to an already mapped drive with drive letter and have it be renamed to the corresponding server?

ex. Q:\\192.168.0.1\Test --> Q:\\Server1\Test

Can I assign "x" to represent "Q:\\192.168.0.1\Test", then in return, have "x" changed to "Q:\\Server1\Test" ?

I am not familiar with PowerShell but I am incorporating it into my scripts now. 

Viewing all 21975 articles
Browse latest View live


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