Fexception
Fexception

Reputation: 167

Powershell could not find part of the path

Been at this for a few hours. I'm trying to grab the software list from a windows machine, and export that list as a CSV using the location as $env:userprofile and the path to the file "Software Inventories\$Username.csv"

I get the following error

Export-Csv : Could not find a part of the path 'C:\Users\mylogin\Software Inventories\@{UserName=domain\mylogin}.csv'.
At C:\Users\mylogin\Dropbox\Powershell\GetSoftwareList.ps1:24 char:191
+ ... e, Vendor, Version | Sort-Object DisplayName | Export-Csv -Path $Path
+                                                    ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Export-Csv], DirectoryNotFoundException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ExportCsvCommand

And the code is as follows:

$ComputerName = Read-Host 'Enter IP or computer name'
$WindowsVersion = Get-WmiObject -ComputerName $ComputerName -Credential 'domain\myadmin' -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption


If ($WindowsVersion -match 'Microsoft Windows 10 Enterprise'){

    $Username = Get-CimInstance -ComputerName $ComputerName -ClassName Win32_ComputerSystem | Select-Object UserName
    $Path = Join-Path $env:userprofile "Software Inventories\$Username.csv"
    Get-CimInstance -ComputerName $ComputerName -Credential "domain\myadmin" -ClassName Win32_InstalledWin32Program | Select Name, Vendor, Version | Sort-Object Name | Export-Csv -Path $Path
    Write-Host "Windows version is $WindowsVersion"

}Elseif ($WindowsVersion -match 'Microsoft Windows 7 Enterprise') {

    $Username = Get-WmiObject -ComputerName $ComputerName -Class Win32_ComputerSystem | Select-Object UserName
    $Path = Join-Path $env:userprofile "Software Inventories\$Username.csv"
    Get-WmiObject -ComputerName $ComputerName -Credential 'domain\myadmin' -Class Win32Reg_AddRemovePrograms | Select DisplayName, Vendor, Version | Sort-Object DisplayName | Export-Csv -Path $Path
    Write-Host "Windows version is $WindowsVersion"

Am I not using Join-Path correctly?

On a side note, how can I grab just the username as a string from $Username and omit the rest?

Upvotes: 0

Views: 5387

Answers (2)

Nas
Nas

Reputation: 1263

$Username = (Get-CimInstance -ComputerName $ComputerName -ClassName Win32_ComputerSystem | Select-Object -ExpandProperty UserName).Split('\')[1]
$Username = (Get-WmiObject -ComputerName $ComputerName -Class Win32_ComputerSystem | Select-Object -ExpandProperty UserName).Split('\')[1]

Upvotes: 2

Jordan
Jordan

Reputation: 413

The variable $UserName is a hashtable with a property named UserName and a value of domain\mylogin. To select only the value of the property, use the ExpandProperty parameter from Select-Object.

$Username = Get-CimInstance -ComputerName $ComputerName -ClassName Win32_ComputerSystem | Select-Object -ExpandProperty UserName

Upvotes: 2

Related Questions